Spring DI同时具有两个构造函数

时间:2019-06-18 09:42:07

标签: java spring dependency-injection javabeans multiple-constructors

这是一种反模式,但我很好奇实际会发生什么。

如果您明确定义了无参数构造函数和带有自动装配参数的构造函数,spring框架将如何精确地对其进行初始化?

@Service
class Clazz {

    private MyBean myBean;

    public Clazz(){}

    @Autowired
    public Clazz(MyBean myBean){
        this.myBean = myBean;
    }
}

3 个答案:

答案 0 :(得分:0)

标记为@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

答案 1 :(得分:0)

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());

答案 2 :(得分:0)

在上述答案之上,如果声明了一个没有@autowire的构造函数,spring将使用相同的构造函数进行注入。

如果有多个构造函数,那么Spring使用@autowired的构造函数。

在Spring Doc https://docs.spring.io/spring/docs/4.3.x/spring-framework-reference/htmlsingle/#beans-autowired-annotation中提到

  

从Spring Framework 4.3开始,在这样的   如果目标bean只定义一个,则不再需要构造函数   构造函数开始。但是,如果有几个构造函数   可用,必须至少注释一个以告知容器   一个使用

相关问题