Spring為什么@Autowired注入的是接口


1.Spring怎么知道注入哪個實現? 
As long as there is only a single implementation of the interface and that implementation is annotated with @Component with Spring’s component scan enabled, Spring framework can find out the (interface, implementation) pair. If component scan is not enabled, then you have to define the bean explicitly in your application-config.xml (or equivalent spring configuration file). 
如果Spring配置了component scan,並且要注入的接口只有一個實現的話,那么spring框架可以自動將interface於實現組裝起來。如果沒有配置component scan,那么你必須在application-config.xml(或等同的配置文件)定義這個bean。

2.需要@Qualifier和@Resource注解嗎? 
Once you have more than one implementation, then you need to qualify each of them and during auto-wiring, you would need to use the @Qualifier annotation to inject the right implementation, along with @Autowired annotation. If you are using @Resource (J2EE semantics), then you should specify the bean name using the name attribute of this annotation. 
一旦一個接口有多個實現,那么就需要每個特殊化識別並且在自動裝載過程中使用@Qualifier和@Autowired一起使用來標明。如果是使用@Resource注解,那么你應該使用resource中屬性名稱來標注@Autowired.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM