您好,登錄后才能下訂單哦!
這篇文章主要介紹Spring中@Autowired注入有什么用,文中介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們一定要看完!
一、同一類型注入多次為同一實例
首先讓我們先看下這段代碼是什么?
@Autowired private XiaoMing xiaoming; @Autowired private XiaoMing wanger;
XiaoMing.java
package com.example.demo.beans.impl; import org.springframework.stereotype.Service; /** * * The class XiaoMing. * * Description:小明 * * @author: huangjiawei * @since: 2018年7月23日 * @version: $Revision$ $Date$ $LastChangedBy$ * */ @Service public class XiaoMing { public void printName() { System.err.println("小明"); } }
我們都知道 @Autowired
可以根據(jù)類型( Type
)進(jìn)行自動注入,并且默認(rèn)注入的bean為單例( SingleTon
)的,那么我們可能會問,上面注入兩次不會重復(fù)嗎?答案是肯定的。而且每次注入的實例都是同一個實例。下面我們簡單驗證下:
@RestController public class MyController { @Autowired private XiaoMing xiaoming; @Autowired private XiaoMing wanger; @RequestMapping(value = "/test.json", method = RequestMethod.GET) public String test() { System.err.println(xiaoming); System.err.println(wanger); return "hello"; } }
調(diào)用上面的接口之后,將輸出下面內(nèi)容,可以看出兩者為同一實例。
com.example.demo.beans.impl.XiaoMing@6afd4ce9
com.example.demo.beans.impl.XiaoMing@6afd4ce9
二、注入接口類型實例
如果我們要注入的類型聲明為一個接口類型,而且該接口有1個以上的實現(xiàn)類,那么下面這段代碼還能夠正常運(yùn)行嗎?我們假設(shè) Student
為接口, WangEr
和 XiaoMing
為兩個實現(xiàn)類。
@Autowired private Student stu1; @Autowired private Student stu2;
@Service public class XiaoMing implements Student {
@Service public class WangEr implements Student {
答案是上面的代碼不能正常運(yùn)行,而且Spring 還啟動報錯了,原因是Spring想為 Student 注入一個單例的實例,但在注入的過程中意外地發(fā)現(xiàn)兩個,所以報錯,具體錯誤信息如下:
Field stu1 in com.example.demo.controller.MyController required a single bean, but 2 were found:
- wangEr: defined in file [C:\Users\huangjiawei\Desktop\demo\target\classes\com\example\demo\beans\impl\WangEr.class]
- xiaoMing: defined in file [C:\Users\huangjiawei\Desktop\demo\target\classes\com\example\demo\beans\impl\XiaoMing.class]
那該怎么弄才行呢?一般思路我們會想到為每個實現(xiàn)類分配一個id值,結(jié)果就有了下面的代碼:
@Autowired private Student stu1; @Autowired private Student stu2;
@Service("stu1") public class XiaoMing implements Student {
@Service("stu2") public class WangEr implements Student {
做完上面的配置之后,Spring就會根據(jù)字段名稱默認(rèn)去bean工廠找相應(yīng)的bean進(jìn)行注入,注意名稱不能夠隨便取的,要和注入的屬性名一致。
三、總結(jié)
同一類型可以使用@Autowired
注入多次,并且所有注入的實例都是同一個實例;
當(dāng)對接口進(jìn)行注入時,應(yīng)該為每個實現(xiàn)類指明相應(yīng)的id,則Spring將報錯;
以上是“Spring中@Autowired注入有什么用”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。