如何解决Spring构造函数注入中的歧义问题

时间:2016-11-05 19:22:35

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

我正在尝试使用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的配置类以确保注入特定的构造函数?

1 个答案:

答案 0 :(得分:0)

取决于您希望如何创建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);
}

}

//确保为其软件包

启用了使用组件和组件扫描注释的地址,城市