在看项目的时候看到了@Primary,因为之前没留意过,所以就去学习了一下,在此记录一下自己的理解,感叹一下还要学习的东西太多了,慢慢加油。
1.概述
@Primary的作用就是当有多个相同类型的bean时,使用@Primary来赋予bean更高的优先级。
比如Spring IOC容器中有多个相同类型的bean时,当要注入该类型的bean,就可以用@Primary来标注注入bean的优先,优先级高的bean先被注入。
2.具体案例
@Configuration
public class Config{
@Bean
public People people1() {
return new People ("用户1");
}
@Bean
public People people2() {
return new People ("用户2");
}
}
//如果尝试运行应用程序,与@Autowired一起应用于注入。
public class Service{
@Autowired
private People p;
//Spring会抛出NoUniqueBeanDefinitionException。
public void use(){
System.out.println(p.speak());
}
}
3.解决办法
1.使用@Qualifier(“beanName”)注解
@Component
@Qualifier("people1 ")
public class People1 implements People{
@Override
public String speaking(String content) {
return "People1 Speaking: "+content;
}
}
@Component
@Qualifier("people2")
public class People2 implements People{
@Override
public String speaking(String content) {
return "People2 Speaking: "+content;
}
//使用
@Component
public class Service{
@Autowired
@Qualifier("prople1")
private People p;
public String speaking(){
return p.speak("how are you");
}
}
2.使用@Primary注解
@Component
public class People1 implements People{
@Override
public String speaking(String content) {
return "People1 Speaking: "+content;
}
}
@Component
@Primary
public class People2 implements People{
@Override
public String speaking(String content) {
return "People2 Speaking: "+content;
}
//@Primary与@Component使用
@Component
public class Service{
@Autowired
private People p;
public String speaking(){
return p.speak("how are you");
}
}
//@Primary与@Bean使用
@Configuration
public class Config{
@Bean
public People people1() {
return new People ("hello,我是people1");
}
@Bean
@Primary
public People people2() {
return new People ("hello,我是people2");
}
}