我有一节课,就像这样
public class testClass {
private TestService testService;
public testClass() {
this(testService);
}
@Autowired(required = true)
public testClass(TestService testService) {
this.testService = testService;
}
}默认的无参数构造函数是强制的,因为我有一个结构化的工厂设计,我从那里调用我的无参数构造函数,所以我不想改变这个结构。所以我用chaining constructor从default constructor调用argumented constructor。但是java抛出了异常
cannot reference testService before supertype constructor has been called,
我可以通过将testService作为static来解决这个异常,但是从here中,我认为使用静态注入并不总是一个好主意。
有没有人可以给我一些设计方案的建议,告诉我如何在没有静态注入的情况下从default constructor中解决或调用这个argumented constructor。
发布于 2015-06-03 13:03:56
您有两个选择:
现场注入
向该字段添加一个@Autowired注释,并丢弃带参数的构造函数。
Spring将使用反射注入依赖项。如果与示例中一样,后面的默认构造函数是空的,并且是唯一的构造函数,那么您也可以丢弃它,因为java编译器会为您创建它。
优点:简短的代码
构造函数注入丢弃了无参数的构造函数。Spring将很好地提供依赖关系。
优点:你的代码在没有Spring的情况下工作得很好,这很棒,还有其他一些测试方面的东西。Here is a more detailed explanation why I prefer this variation。
一些额外的评论:
https://stackoverflow.com/questions/30611039
复制相似问题