javascript
Spring3:类型安全依赖项注入
像這樣的東西會(huì)注入Spring Bean。 @Autowired private StudentDao studentDao; // Autowires by type. Injects the instance whose type is StudentDao
但是,如果我們有一種類(lèi)型的多個(gè)Spring bean,那么我們將使用Qualifier Annotation和Autowired,實(shí)際上是按名稱(chēng)注入spring bean。
具有以下內(nèi)容的應(yīng)用程序上下文:
<bean id="studentDao1" class="StudentDao" /> <bean id="studentDao2" class="StudentDao" />因此,如果現(xiàn)在有兩個(gè)StudentDao實(shí)例(studentDao1和studentDao2),則可以按名稱(chēng)注入spring bean。
@Autowired @Qualifier("studentDao1") private StudentDao studentDao1;@Autowired @Qualifier("studentDao2") private StudentDao studentDao2; 使用JSR-250指定的資源注釋可以實(shí)現(xiàn)相同的目的。 因此,我們可以使用此注釋將bean注入到字段或單參數(shù)方法中。 自動(dòng)裝配比Resource靈活得多,因?yàn)樗梢耘c多參數(shù)方法以及構(gòu)造函數(shù)一起使用。
我們可以通過(guò)以下方式使用Resource注解按名稱(chēng)注入bean。
Spring 3中的類(lèi)型安全依賴(lài)項(xiàng)注入
使用@Qualifier定義自定義注釋
要在不指定名稱(chēng)的情況下識(shí)別注入的bean,我們需要?jiǎng)?chuàng)建一個(gè)自定義注釋。 這等效于在CDI中使用JSR 330批注(Inject)的過(guò)程。
@Target({ElementType.Field, ElementType.Parameter}) @Retention(RetentionPolicy.RUNTIME) @Qualifier public @Interface Student { }現(xiàn)在將此自定義注釋分配給EntityDao接口的實(shí)現(xiàn)
@Component @Student public class StudentDao implements EntityDao { } @Component告訴Spring這是一個(gè)bean定義。 每當(dāng)使用EntityDao的引用時(shí),Spring IoC就會(huì)使用@Student批注將StudentDao標(biāo)識(shí)為EntityDao的實(shí)現(xiàn)。
使用@Autowired和自定義限定符注入bean
這樣的東西。
這減少了字符串名稱(chēng)的使用,因?yàn)樽址Q(chēng)可能會(huì)拼寫(xiě)錯(cuò)誤并且難以維護(hù)。
參考: 如何在Spring 3中使用類(lèi)型安全依賴(lài)項(xiàng)注入? 來(lái)自我們的JCG合作伙伴 Saurab Parakh在Coding is Cool博客上。
翻譯自: https://www.javacodegeeks.com/2012/05/spring-3-type-safe-dependency-injection.html
總結(jié)
以上是生活随笔為你收集整理的Spring3:类型安全依赖项注入的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 测试路由器手机无线性能如何测试路由器的实
- 下一篇: 教程:Hibernate,JPA和Spr