问题
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
回答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.
回答2:
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.
来源:https://stackoverflow.com/questions/35372707/how-to-avoid-repetitive-constructor-in-children