1. 程式人生 > >註解@primary解析

註解@primary解析

spring中少見的註解@primary註解,例子

@Component  
public class MetalSinger implements Singer{  

    @Override  
    public String sing(String lyrics) {  
        return "I am singing with DIO voice: "+lyrics;  
    }  
}  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
public class OperaSinger implements Singer {  
    @Override  
    public String sing
(String lyrics) { return "I am singing in Bocelli voice: "+lyrics; } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

這兩個類都實現了singer介面

public interface Singer {  
    String sing(String lyrics);  
}  
  • 1
  • 2
  • 3

那麼來個注入的:

@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"); } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

那麼最後輸出應該是: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;  
    }  
}