spring中少用的注解@primary解析

分类: 转载文章 0人评论 dexcoder 1年前发布
这次看下spring中少见的注解@primary注解,例子
@Component
public class MetalSinger implements Singer{
    @Override
    public String sing(String lyrics) {
        return "I am singing with DIO voice: "+lyrics;
    }
}
 
public class OperaSinger implements Singer {
    @Override
    public String sing(String lyrics) {
        return "I am singing in Bocelli voice: "+lyrics;
    }
}
  这两个类都实现了singer接口  
public interface Singer {
    String sing(String lyrics);
}
  那么来个注入的:
@Component
public class SingerService {
    private static final Logger logger = LoggerFactory.getLogger(SingerService.class);
    @Autowired
    private Singer singer;
    public String sing(){
        return singer.sing("song lyrics");
    }
}

   那么最后输出应该是:I am singing with DIO voice: song lyrics. 

原因是只有MetalSinger使用了注解@component,那么autowird会只寻找这个标记的 进行注入:   如果也在OperaSinger 中使用了注解,则spring会报异常,不知道到底应该用 哪个:   org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [main.service.Singer] is defined: expected single matching bean but found 2: metalSinger,operaSinger  

而如果要让spring知道必须注入的是OperaSinger ,则可以用@primary注解告诉 spring:   

@Primary
@Component
public class OperaSinger implements Singer{
    @Override
    public String sing(String lyrics) {
        return "I am singing in Bocelli voice: "+lyrics;
    }
}      
上一篇:
下一篇:

你可能感兴趣的文章

0 条评论