這篇文章主要介紹Spring中@Autowired注入有什么用,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!

創新互聯專注于企業成都全網營銷、網站重做改版、柴桑網站定制設計、自適應品牌網站建設、H5響應式網站、成都做商城網站、集團公司官網建設、成都外貿網站建設公司、高端網站制作、響應式網頁設計等建站業務,價格優惠性價比高,為柴桑等各大城市提供網站開發制作服務。
一、同一類型注入多次為同一實例
首先讓我們先看下這段代碼是什么?
@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 可以根據類型( Type )進行自動注入,并且默認注入的bean為單例( SingleTon )的,那么我們可能會問,上面注入兩次不會重復嗎?答案是肯定的。而且每次注入的實例都是同一個實例。下面我們簡單驗證下:
@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";
}
}調用上面的接口之后,將輸出下面內容,可以看出兩者為同一實例。
com.example.demo.beans.impl.XiaoMing@6afd4ce9
com.example.demo.beans.impl.XiaoMing@6afd4ce9
二、注入接口類型實例
如果我們要注入的類型聲明為一個接口類型,而且該接口有1個以上的實現類,那么下面這段代碼還能夠正常運行嗎?我們假設 Student 為接口, WangEr 和 XiaoMing 為兩個實現類。
@Autowired private Student stu1; @Autowired private Student stu2;
@Service
public class XiaoMing implements Student {@Service
public class WangEr implements Student {答案是上面的代碼不能正常運行,而且Spring 還啟動報錯了,原因是Spring想為 Student 注入一個單例的實例,但在注入的過程中意外地發現兩個,所以報錯,具體錯誤信息如下:
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]
那該怎么弄才行呢?一般思路我們會想到為每個實現類分配一個id值,結果就有了下面的代碼:
@Autowired private Student stu1; @Autowired private Student stu2;
@Service("stu1")
public class XiaoMing implements Student {@Service("stu2")
public class WangEr implements Student {做完上面的配置之后,Spring就會根據字段名稱默認去bean工廠找相應的bean進行注入,注意名稱不能夠隨便取的,要和注入的屬性名一致。
三、總結
同一類型可以使用@Autowired注入多次,并且所有注入的實例都是同一個實例;
當對接口進行注入時,應該為每個實現類指明相應的id,則Spring將報錯;
以上是“Spring中@Autowired注入有什么用”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注創新互聯行業資訊頻道!
網頁標題:Spring中@Autowired注入有什么用
標題網址:http://www.yijiale78.com/article16/jceedg.html
成都網站建設公司_創新互聯,為您提供域名注冊、網站建設、定制網站、自適應網站、App設計、網站改版
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯