Spring中@Primary注解的作用详解
@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

到此这篇关于Spring中@Primary注解的作用详解的文章就介绍到这了,更多相关@Primary注解的作用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
Maven介绍与配置+IDEA集成Maven+使用Maven命令小结
Maven是Apache软件基金会的一个开源项目,是一个优秀的项目构建管理工具,它用来帮助开发者管理项目中的 jar,以及 jar 之间的依赖关系、完成项目的编译、测试、打包和发布等工作,本文给大家介绍Maven介绍与配置+IDEA集成Maven+使用Maven命令,感兴趣的朋友一起看看吧2024-01-01


最新评论