@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