javascript
spring依赖注入_Spring3:类型安全依赖项注入
spring依賴注入
在從Spring跳到類型安全依賴注入之前,我想討論一下我們之前所做的方式。 我們一直在借助Spring的Autowired注釋按類型使用依賴項(xiàng)注入。像這樣的東西會注入Spring Bean。 @Autowired private StudentDao studentDao; // Autowires by type. Injects the instance whose type is StudentDao
但是,如果我們有一種類型的多個(gè)Spring bean,那么我們將使用Qualifier Annotation和Autowired,實(shí)際上是按名稱注入spring bean。
具有以下內(nèi)容的應(yīng)用程序上下文:
<bean id="studentDao1" class="StudentDao" /> <bean id="studentDao2" class="StudentDao" />因此,現(xiàn)在如果我們有兩個(gè)StudentDao實(shí)例(studentDao1和studentDao2),則可以按名稱注入spring bean。
@Autowired @Qualifier("studentDao1") private StudentDao studentDao1;@Autowired @Qualifier("studentDao2") private StudentDao studentDao2; 使用JSR-250指定的資源注釋可以實(shí)現(xiàn)相同的目的。 因此,我們可以使用此注釋將bean注入到字段或單參數(shù)方法中。 自動裝配比Resource靈活得多,因?yàn)樗梢耘c多參數(shù)方法以及構(gòu)造函數(shù)一起使用。
我們可以通過以下方式使用Resource注解按名稱注入bean。
Spring 3中的類型安全依賴項(xiàng)注入
使用@Qualifier定義自定義注釋
要在不指定名稱的情況下識別注入的bean,我們需要?jiǎng)?chuàng)建一個(gè)自定義注釋。 這等效于在CDI中使用JSR 330批注(Inject)的過程。
@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都使用@Student注釋將StudentDao標(biāo)識為EntityDao的實(shí)現(xiàn)。
使用@Autowired和自定義限定符注入bean
這樣的事情。
這減少了字符串名稱的使用,因?yàn)樽址Q可能會拼寫錯(cuò)誤并且難以維護(hù)。
參考: 如何在Spring 3中使用類型安全依賴項(xiàng)注入? 來自我們的JCG合作伙伴 Saurab Parakh在Coding is Cool博客上。
翻譯自: https://www.javacodegeeks.com/2012/05/spring-3-type-safe-dependency-injection.html
spring依賴注入
總結(jié)
以上是生活随笔為你收集整理的spring依赖注入_Spring3:类型安全依赖项注入的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何做现货黄金交易?
- 下一篇: gradle idea java ssm