【发布时间】:2016-02-12 21:45:55
【问题描述】:
我有一个父类,它的构造函数为:
@Inject
public AbstractResource(@Named("authorization") Authorization auth,
@Named("helper") Helper helper) {
this.authorization = authorization;
this.helper = helper;
}
现在在子类中,我有类似的构造函数:
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();
}
...
问题是我有大量从 AbstractResource 扩展的子类,我必须再次使用“Authorization”和“Helper”编写类似的构造函数。有什么办法可以避免重复编码?
抱歉,更新了我的代码,是的,我可以在每个子类中调用 super(..),但我仍然在每个构造函数中注入了所有这些参数,auth 和 helper,只是想知道是否有一种方法可以简化那个
【问题讨论】:
-
使用构造函数注入,没有。但如果你觉得没问题,你可以使用 setter 或字段注入。
-
几乎被骗了,但我认为您对 Guice 或 Spring 案例感兴趣 stackoverflow.com/questions/1644317/…