@Primary注解作用详解

本文详细介绍了Spring框架中的@Primary注解在bean定义中的作用,如何解决多实现组件注入冲突,并通过实例演示了如何确保默认Bean的选择。此外,还讨论了如何在多实现接口场景中正确使用@Primary来指定默认组件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

@Primary注解作用详解

       此注解时为了标识哪个Bean是默认的Bean

	  @Bean
	  public AMapper aMapper1(AConfig aConfig) {
	    return new AMapperImpl1(aConfig);
	  }
	
	  @Bean
	  @Primary
	  public AMapper aMapper2(AConfig aConfig) {
	    return new AMapperImpl2(aConfig);
	  }

      上述代码,当存在多个相同类型的Bean注入时,加上@Primary注解,来确定默认的实现标识。

案例
	public interface Worker {
	    public String work();
	}
	
	@Component
	public class Singer implements Worker {
	    @Override
	    public String work() {
	        return "歌手的工作是唱歌";
	    }
	}
	
	@Component
	public class Doctor implements Worker {
	    @Override
	    public String work() {
	        return "医生工作是治病";
	    }
	}
	
	// 启动,调用接口
	@SpringBootApplication
	@RestController
	public class SimpleWebTestApplication {
	
	    @Autowired
	    private Worker worker;
	
	    @RequestMapping("/info")
	    public String getInfo(){
	        return worker.work();
	    }
	
	    public static void main(String[] args) {
	        SpringApplication.run(SimpleWebTestApplication.class, args);
	    }
	
	}

      上述情况下,一个接口多个实现,并且通过@Autowired注入 Worker, 由于@Autowired是通过ByType的形式,来给指定的字段和方法来注入所需的外部资源,
但由于此类有多个实现,Spring不知道注入哪个实现,所以在启动的时候会抛出异常。

	Consider marking one of the beans as @Primary, 
	updating the consumer to accept multiple beans, 
	or using @Qualifier to identify the bean that should be consumed。

      当给指定的组件添加@primary后,默认会注入@Primary的配置组件。

@Component
@Primary
public class Doctor implements Worker {
    @Override
    public String work() {
        return "医生工作是治病";
    }
}

给Doctor 加上@Primary,则默认注入的就是 Doctor 的实现。 浏览器访问:localhost:8080/info
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值