spring笔记-@Primary注解

时间:2021-10-16 16:50:53

1.问题

当一个接口有2个不同实现时,使用@Autowired注解时会报org.springframework.beans.factory.NoUniqueBeanDefinitionException异常信息

2.方案1-@Qualifier

使用Qualifier注解,选择一个对象的名称,通常比较常用

3. 方案2-@Primary

Primary可以理解为默认优先选择,同时不可以同时设置多个,
内部实质是设置BeanDefinition的primary属性

spring笔记-@Primary注解

示例

@Component("metalSinger") // 加注解,让spring识别
public class MetalSinger implements Singer{ @Override
public String sing(String lyrics) {
return "I am singing with DIO voice: "+lyrics;
}
} @Primary
@Component("operaSinger")
public class OperaSinger implements Singer {
@Override
public String sing(String lyrics) {
return "I am singing in Bocelli voice: "+lyrics;
}
} public interface Singer {
String sing(String lyrics);
} @Component
public class SingerService {
private static final Logger logger = LoggerFactory.getLogger(SingerService.class);
@Autowired
@Qualifier
private Singer singer;
public String sing(){
return singer.sing("song lyrics");
} public static void main(String[] args) { ApplicationContext context = new AnnotationConfigApplicationContext("context.annotation.primary");
SingerService singerService = context.getBean(SingerService.class);
System.out.println(singerService.sing());
} }