国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發(fā) > Java > 正文

詳解Spring @Autowired 注入小技巧

2024-07-14 08:41:48
字體:
供稿:網(wǎng)友

今天和同事討論到Spring自動注入時,發(fā)現(xiàn)有這么一段代碼特別地困惑,當然大致的原理還是可以理解的,只不過以前從來沒有這么用過。想到未來可能會用到,或者未來看別人寫的代碼時不至于花時間解決同樣的困惑,所以小編還是覺得有必要研究記錄一下。

一、同一類型注入多次為同一實例

首先讓我們先看下這段代碼是什么?

@Autowiredprivate XiaoMing xiaoming;@Autowiredprivate 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$ * */@Servicepublic class XiaoMing {  public void printName() {  System.err.println("小明"); }}

我們都知道 @Autowired 可以根據(jù)類型( Type )進行自動注入,并且默認注入的bean為單例( SingleTon )的,那么我們可能會問,上面注入兩次不會重復(fù)嗎?答案是肯定的。而且每次注入的實例都是同一個實例。下面我們簡單驗證下:

@RestControllerpublic 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)類,那么下面這段代碼還能夠正常運行嗎?我們假設(shè) Student 為接口, WangEr 和 XiaoMing 為兩個實現(xiàn)類。

@Autowiredprivate Student stu1;@Autowiredprivate Student stu2;
@Servicepublic class XiaoMing implements Student {
@Servicepublic class WangEr implements Student {

答案是上面的代碼不能正常運行,而且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é)果就有了下面的代碼:

@Autowiredprivate Student stu1;@Autowiredprivate Student stu2;
@Service("stu1")public class XiaoMing implements Student {
@Service("stu2")public class WangEr implements Student {

做完上面的配置之后,Spring就會根據(jù)字段名稱默認去bean工廠找相應(yīng)的bean進行注入,注意名稱不能夠隨便取的,要和注入的屬性名一致。

三、總結(jié)

  1. 1、同一類型可以使用@Autowired注入多次,并且所有注入的實例都是同一個實例;
  2. 2、當對接口進行注入時,應(yīng)該為每個實現(xiàn)類指明相應(yīng)的id,則Spring將報錯;

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網(wǎng)。


注:相關(guān)教程知識閱讀請移步到JAVA教程頻道。
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 环江| 潼南县| 临夏市| 瑞安市| 改则县| 库车县| 赤水市| 余干县| 关岭| 东乌珠穆沁旗| 微山县| 阿坝| 渭南市| 清河县| 古交市| 丰县| 卫辉市| 东安县| 广宗县| 通海县| 阳谷县| 嘉峪关市| 红桥区| 仁怀市| 丽水市| 九龙城区| 深水埗区| 灌阳县| 南宫市| 博野县| 和平区| 扎鲁特旗| 德兴市| 阳新县| 汕尾市| 河南省| 东方市| 金门县| 本溪| 文成县| 治多县|