繁体   English   中英

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

[英]Spring DI having two constructors at the same time

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

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

@Service
class Clazz {

    private MyBean myBean;

    public Clazz(){}

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

@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

Spring首先通过最大数量的参数选择构造函数

sortConstructors考虑优先使用公共构造函数和具有最大数量参数的构造函数。

含义Clazz(MyBean myBean)

这是使用的比较器

 (e1, e2) -> { int result = Boolean.compare(Modifier.isPublic(e2.getModifiers()), Modifier.isPublic(e1.getModifiers())); return result != 0 ? result : Integer.compare(e2.getParameterCount(), e1.getParameterCount()); 

在上述答案之上,如果声明了一个没有@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仅定义一个开始的构造函数,则不再需要在此类构造函数上使用@Autowired批注。 但是,如果有几个构造函数可用,则必须至少注释一个,以告诉容器使用哪个构造函数

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM