日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

spring依赖注入_Spring3:类型安全依赖项注入

發(fā)布時(shí)間:2023/12/3 javascript 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 spring依赖注入_Spring3:类型安全依赖项注入 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

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。

@Resource private StudentDao studentDao1;

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
這樣的事情。

@Autowired @Student private EntityDao studentDao; // So the spring injects the instance of StudentDao here.

這減少了字符串名稱的使用,因?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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。