@Primary注解

在看项目的时候看到了@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");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值