【问题标题】:How to resolve ambiguity in Spring constructor injection如何解决 Spring 构造函数注入中的歧义
【发布时间】:2017-03-19 10:38:28
【问题描述】:

我正在尝试使用 Spring 4.3 学习构造函数注入。

我的班级结构如下所述。

@Component     
public class Student {    

private Address address;
private City city;

public Student(Address address, City city) {
    this.address = address;
    this.city = city;
}

public Student(City city, Address address) {
    this.address = address;
    this.city = city;
}

public Student(City city) {
    this.city = city;
}

public Student(Address address) {
    this.address = address;
}
}

基于 Java 的配置类:

@Configuration
@ComponentScan(basePackages = "com.spring.ConstructorInjection")
public class StudentConfiguration {

}

客户端代码:

   ApplicationContext context = new  AnnotationConfigApplicationContext(StudentConfiguration.class);
   Student student = context.getBean(Student.class);
   System.out.println(student.getCity());
   System.out.println(student.getAddress());

如何构建基于 java 的配置类以确保注入特定的构造函数?

【问题讨论】:

  • Address 和 City 是其他春豆吗?如果是这样,请在您希望 Spring 使用的构造函数上添加 @Autowired 注释。不过,不确定为什么需要所有其他构造函数。
  • 是的地址和城市是春豆。我可能有多个要求,我们将需要多个构造函数。那我们如何配置?
  • 这些要求没有多大意义。提出要求的人不应该关心开发人员选择使用多少构造函数和类来使应用程序按要求工作。我不明白你的最后一个问题。

标签: spring dependency-injection spring-4 constructor-injection spring-ioc


【解决方案1】:

取决于您希望如何创建 bean 以及配置文件,您可以在运行时激活它

@Configuration
@ComponentScan(basePackages = "com.spring.ConstructorInjection")
public class StudentConfiguration {

//occasion live
@Bean
@Profile("live")
public Student getStudent(Address address, City city){
    return new Student(address,city);
}

//occasion test
@Bean
@Profile("test")
public Student getStudent(Address address){
    return new Student(address);
}


//occasion throwaway
@Bean
@Profile("throwaway")
public Student getStudent(City city){
    return new Student(city);
}

}

//确保你的地址,城市注释组件和组件扫描为其包启用

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多