[英]using @Qualifier + @Bean(autowire=Autowire.BY_TYPE) in javaConfig
I have an Employee bean having Address type of dependency. 我有一个具有依赖类型的地址的Employee bean。 I'm trying to configure autowiring in javaConfig. 我正在尝试在javaConfig中配置自动装配。 But getting NoQualifyingBeanException
. 但是得到NoQualifyingBeanException
。
Although I'm using @Qualifier()
annotation as follow : 虽然我使用@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;
}
}
Specifying a different name
attribute in each @Bean
method is not enough. 在每个@Bean
方法中指定不同的name
属性是不够的。
You should consider marking one of the beans as @Primary
: 您应该考虑将其中一个bean标记为@Primary
:
@Primary
@Bean(name = "address")
public Address addressAgain() {
return new Address("See You");
}
And leave the other(s) without : 并让其他人不要:
@Bean(name="addr1")
public Address address() {
return new Address("Hello","hi", 112233);
}
Note that you don't need to add the @Qualifier("addr1")
annotation in the employee()
method to be able to autowire the addr1
bean. 请注意,您无需在employee()
方法中添加@Qualifier("addr1")
批注即可自动装配addr1
bean。
Spring already knows the Address
bean instance you refer to as you set the dependency from a @Bean
method : address()
. 当您通过@Bean
方法设置依赖项时,Spring已经知道您所引用的Address
Bean实例: address()
。
So it is enough : 这样就足够了:
@Bean(name = "emp", autowire = Autowire.BY_TYPE)
public Employee employee() {
Employee e = new Employee();
e.setName("Raghu");
e.setAddress(address());
return e;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.