【问题标题】: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


    【解决方案1】:

    在上述答案之上,如果声明了一个没有@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 开始,@Autowired 注释在这样的 如果目标 bean 只定义了一个,则不再需要构造函数 构造函数开始。但是,如果有多个构造函数 可用,必须至少注释一个以教导容器 一个使用

    【讨论】:

      【解决方案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());
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-04-04
          • 1970-01-01
          • 1970-01-01
          • 2017-03-29
          • 2014-05-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多