2

I have a parent class, which has constructor as:

    @Inject
    public AbstractResource(@Named("authorization") Authorization auth,
                            @Named("helper") Helper helper) {
        this.authorization = authorization;
        this.helper = helper;
    }

now in the children class, i have similar constructor:

public class MyResource extends AbstractResource {
        private Manager manager;

        @Inject
        public MyResource(@Named("authorization") Authorization auth,
                          @Named("helper") Helper helper) {
            super(auth, helper);
            this.manager = new Manager();
        }
...

Problem is I have tons of children class extend from AbstractResource, I have to write the similar constructor with 'Authorization' and 'Helper' again and agin. is there any way i can avoid the repetitive coding?

Sorry, updated my code, yes, i can call super(..) in each children class, but still in each constructor i have inject all those parameters, auth and helper, just wonder if there is a way to even simplify that

JB Nizet
  • 657,433
  • 87
  • 1,179
  • 1,226
user468587
  • 4,345
  • 21
  • 60
  • 111
  • With constructor injection, no. But you could use setter or field injection if you find it fine. – JB Nizet Feb 12 '16 at 21:48
  • almost dupe but I think you're interested in the Guice or Spring case http://stackoverflow.com/questions/1644317/java-constructor-inheritance – djechlin Feb 12 '16 at 21:49

2 Answers2

1

Unless I'm missing something about this there is a simple solution by calling through to the parent's constructor.

In your child class's constructor the first line should be: super(authorization, helper)

EDIT: Author has edited his question so this solution is no longer applicable.

Charles Durham
  • 2,345
  • 15
  • 16
1

You can create an object to hold all the arguments.

But other than that, no not really. This is what production DI code in Java actually looks like.

djechlin
  • 57,408
  • 33
  • 153
  • 271