【问题标题】:Spring DI having two constructors at the same timeSpring DI 同时具有两个构造函数
【发布时间】:2019-10-31 22:11:20
【问题描述】:
这是一种反模式,但我很好奇实际会发生什么。
如果你显式定义了一个无参数的构造函数和一个带有自动装配参数的构造函数,那么spring框架将如何初始化它?
@Service
class Clazz {
private MyBean myBean;
public Clazz(){}
@Autowired
public Clazz(MyBean myBean){
this.myBean = myBean;
}
}
【问题讨论】:
标签:
java
spring
dependency-injection
javabeans
multiple-constructors
【解决方案2】:
@Autowired标记的构造函数将被spring使用。您可以通过运行以下代码来验证这一点。
public class Main {
@Component
static class MyBean {}
@Service
static class Clazz {
private MyBean myBean;
public Clazz(){
System.out.println("empty");
}
@Autowired
public Clazz(MyBean myBean){
this.myBean = myBean;
System.out.println("non-empty");
}
}
@Component
@ComponentScan("my.package")
private static class Configuration {
}
public static void main(String[] args) {
var ctx = new AnnotationConfigApplicationContext();
ctx.register(Configuration.class);
ctx.refresh();
ctx.getBean(Clazz.class);
}
}
代码打印non-empty。
【解决方案3】:
Spring首先通过largest number of parameters选择构造函数
sortConstructors 考虑优先考虑公共构造函数和具有最大参数数量的构造函数。
含义Clazz(MyBean myBean)
这是Comparator used:
(e1, e2) -> {
int result = Boolean.compare(Modifier.isPublic(e2.getModifiers()), Modifier.isPublic(e1.getModifiers()));
return result != 0 ? result : Integer.compare(e2.getParameterCount(), e1.getParameterCount());