我有一个具有Address依赖类型的Employee bean。我正在尝试在javaConfig中配置自动装配。但是获得NoQualifyingBeanException
虽然我使用@Qualifier()
注释如下:
@Configuration
public class MyConfig {
@Bean(name="addr1")
public Address address() {
return new Address("Hello","hi",112233);
}
@Bean(name="address")
public Address addressAgain() {
return new Address("See You","Bi",114422);
}
@Bean(name="emp",autowire=Autowire.BY_TYPE)
@Qualifier("addr1")
public Employee employee() {
Employee e = new Employee();
e.setName("Raghu");
e.setEmpID(111);
//e.setAddress(address());
return e;
}
}
答案 0 :(得分:0)
在每个name
方法中指定不同的@Bean
属性是不够的
您应该考虑将其中一个bean标记为@Primary
:
@Primary
@Bean(name = "address")
public Address addressAgain() {
return new Address("See You");
}
离开其他人没有:
@Bean(name="addr1")
public Address address() {
return new Address("Hello","hi", 112233);
}
请注意,您不需要在@Qualifier("addr1")
方法中添加employee()
注释,以便能够自动装配addr1
bean。
当您从Address
方法设置依赖项时,Spring已经知道您引用的@Bean
bean实例:address()
。
这就足够了:
@Bean(name = "emp", autowire = Autowire.BY_TYPE)
public Employee employee() {
Employee e = new Employee();
e.setName("Raghu");
e.setAddress(address());
return e;
}