日韩成人免费在线_国产成人一二_精品国产免费人成电影在线观..._日本一区二区三区久久久久久久久不

當前位置:首頁 > 科技  > 軟件

一個很有意思的Spring注入問題,你遇到過嗎?

來源: 責編: 時間:2024-03-18 09:36:48 229觀看
導讀環境:Spring5.3.231. 問題描述static interface DAO {}static class CommonDAO implements DAO {}@Configurationstatic class AppConfig { @Bean DAO dao() { return new CommonDAO() ; }}static class CommonS

環境:Spring5.3.23bIM28資訊網——每日最新資訊28at.com

1. 問題描述

static interface DAO {}static class CommonDAO implements DAO {}@Configurationstatic class AppConfig {  @Bean  DAO dao() {    return new CommonDAO() ;  }}static class CommonService {  @Resource  private DAO dao ;  @Resource  private CommonDAO commonDAO ;}try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) {  context.registerBean(AppConfig.class) ;  context.registerBean(CommonService.class) ;  context.refresh() ;}

上面是基本的bean定義。在AppConfig配置類中定義了DAO bean實例,在CommonService中分別去注入DAO 接口和CommonDAO。運行上面的程序沒有問題正常。bIM28資訊網——每日最新資訊28at.com

2. 問題匯總

2.1 修改注入1

static class CommonService {  @Resource  private CommonDAO commonDAO ;}

當CommonService只注入CommonDAO時,程序既然報錯了bIM28資訊網——每日最新資訊28at.com

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.pack.main.bean_propertyvalue_inject.InterfaceAndImplInject$CommonDAO' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@javax.annotation.Resource(shareable=true, lookup=, name=, description=, authenticationType=CONTAINER, type=class java.lang.Object, mappedName=)}  at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1801)  at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1357)

錯誤提示:需要CommonDAO但是容器中沒有,是不是很奇怪。bIM28資訊網——每日最新資訊28at.com

2.2. 修改注入2

static class CommonService {  @Resource  private CommonDAO dao;}

只是吧字段的名稱修改為dao,程序又正確了。這個什么原因???bIM28資訊網——每日最新資訊28at.com

2.3 修改注入3

static class CommonService {  @Resource  private CommonDAO commonDAO ;  @Resource  private DAO dao ;}

這里僅僅是修改了下字段的順序,程序又報錯了,是不是太神奇了。bIM28資訊網——每日最新資訊28at.com

2.4 修改注入4

@Configurationstatic class AppConfig {  @Bean  CommonService commonService() {    return new CommonService() ;  }  @Bean  DAO dao() {    return new CommonDAO() ;  }}static class CommonService {  @Resource  private CommonDAO commonDAO ;}

修改了CommonService bean的注冊方式,運行程序還是錯誤bIM28資訊網——每日最新資訊28at.com

2.5 修改注入5

@Configurationstatic class AppConfig {  @Bean  DAO dao() {    return new CommonDAO() ;  }  @Bean  CommonService commonService() {    return new CommonService() ;  }}

根據2.4的情況,修改注冊DAO與CommonService的順序后,程序又正確了。bIM28資訊網——每日最新資訊28at.com

3. 原因解析

當如下方式注入時bIM28資訊網——每日最新資訊28at.com

@Resourceprivate DAO dao ;@Resourceprivate CommonDAO commonDAO ;

提示:@Resource注解對應的處理器是CommonAnnotationBeanPostProcessorbIM28資訊網——每日最新資訊28at.com

這里首先要整清楚@Resource的注入方式bIM28資訊網——每日最新資訊28at.com

@Resource先根據beanName進行查找,再通過類型查找。源碼:bIM28資訊網——每日最新資訊28at.com

public class CommonAnnotationBeanPostProcessor {  protected Object autowireResource(BeanFactory factory, LookupElement element, @Nullable String requestingBeanName) {    Object resource;    if (factory instanceof AutowireCapableBeanFactory) {      AutowireCapableBeanFactory beanFactory = (AutowireCapableBeanFactory) factory;      DependencyDescriptor descriptor = element.getDependencyDescriptor();      // 判斷你當前注入屬性的名字(beanName) 在容器中是否存在。這里取反了,如果不存在時進行類型的查找      if (this.fallbackToDefaultTypeMatch && element.isDefaultName && !factory.containsBean(name)) {        resource = beanFactory.resolveDependency(descriptor, requestingBeanName, autowiredBeanNames, null);      } else {        // 存在,直接通過beanName(這里就是字段名)查找        resource = beanFactory.resolveBeanByName(name, descriptor);        autowiredBeanNames = Collections.singleton(name);      }    }    return resource;  }}

上面你知道了@Resource注解的方式注入的方式后。接下來就是查找具體的bean了,不管是通過beanName還是類型。這里演示還是按照beanName方式,接著上面的代碼bIM28資訊網——每日最新資訊28at.com

public abstract class AbstractAutowireCapableBeanFactory {  public Object resolveBeanByName(String name, DependencyDescriptor descriptor) {    return getBean(name, descriptor.getDependencyType());  }}public abstract class AbstractBeanFactory {  public <T> T getBean(String name, Class<T> requiredType) throws BeansException {    return doGetBean(name, requiredType, null, false);  }  protected <T> T doGetBean(    String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly) {    // 這里就是先從單例池中獲取指定beanName是否存在,如果不存在則進行創建bean實例。    // 創建完成后將當前的實例存入單例池中。  }}

到此,DAO類型的屬性就注入成功了,接下是注入CommonDAO。注入CommonDAO由于容器中沒有對應的beanName,所有進入上面的if語句中。bIM28資訊網——每日最新資訊28at.com

public class DefaultListableBeanFactory {  public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName,    @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {    // ...    Object result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter);  }  public Object doResolveDependency(...) {    // ...    Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor);  }  protected Map<String, Object> findAutowireCandidates(    @Nullable String beanName, Class<?> requiredType, DependencyDescriptor descriptor) {    // 通過類型查找beanNames, 當前reqiredType=CommonDAO    String[] candidateNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(        this, requiredType, true, descriptor.isEager());  }}public abstract class BeanFactoryUtils {  public static String[] beanNamesForTypeIncludingAncestors(      ListableBeanFactory lbf, Class<?> type, boolean includeNonSingletons, boolean allowEagerInit) {    // 通過類型查找    String[] result = lbf.getBeanNamesForType(type, includeNonSingletons, allowEagerInit);    return result;  }}public class DefaultListableBeanFactory {  public String[] getBeanNamesForType(@Nullable Class<?> type, boolean includeNonSingletons, boolean allowEagerInit) {    // 通過類型查找    String[] resolvedBeanNames = doGetBeanNamesForType(ResolvableType.forRawClass(type), includeNonSingletons, true);    return resolvedBeanNames;  }  private String[] doGetBeanNamesForType(ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit) {    // 遍歷所有的BeanDefinition(這是Spring容器對每一個bena的元數據了)    for (String beanName : this.beanDefinitionNames) {      RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName) ;      // 關鍵代碼      matchFound = isTypeMatch(beanName, type, true);    }  }  protected boolean isTypeMatch(String name, ...) {    // beanName = dao    String beanName = transformedBeanName(name);    // 從單例池中獲取實例,這里肯定可以獲取,我們第一個屬性注入的就是    // DAO,所以這里就返回了CommonDAO實例    Object beanInstance = getSingleton(beanName, false);    if (beanInstance != null && beanInstance.getClass() != NullBean.class) {      // 這里肯定是實例對象,直接返回了      if (typeToMatch.isInstance(beanInstance)) {        return true;      }    }  }}

到這你應該清楚了為什么同時有DAO和CommonDAO注入時能成功了。但是當沒有DAO注入的時候為什么就錯誤呢?原因其實在上面已經給出了,你只要包裝我在注入CommonDAO時,容器中已經將DAO這個bean實例創建存入到單例池中即可。這也就是為什么上面我們調整合理的順序后就能注入成功。還有就是你可以將CommonDAO的字段名稱改成與DAO bean的beanName一致也是可以的。bIM28資訊網——每日最新資訊28at.com

以上是本篇文章的全部內容,希望對你有幫助。bIM28資訊網——每日最新資訊28at.com

完畢?。?!bIM28資訊網——每日最新資訊28at.com

本文鏈接:http://www.www897cc.com/showinfo-26-76486-0.html一個很有意思的Spring注入問題,你遇到過嗎?

聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com

上一篇: 沒看過ReentrantLock源碼,別說精通Java并發編程

下一篇: JQuery 4.0震撼發布:這是復興還是告別?

標簽:
  • 熱門焦點
  • 一加Ace2 Pro官宣:普及16G內存 引領24G

    一加官方今天繼續為本月發布的新機一加Ace2 Pro帶來預熱,公布了內存方面的信息?!疤蕴?8GB ,12GB 起步,16GB 普及,24GB 引領,還有呢?#一加Ace2Pro#,2023 年 8 月,敬請期待?!蓖瑫r
  • 企業采用CRM系統的11個好處

    客戶關系管理(CRM)軟件可以為企業提供很多的好處,從客戶保留到提高生產力。  CRM軟件用于企業收集客戶互動,以改善客戶體驗和滿意度?! RM軟件市場規模如今超過580
  • JavaScript學習 -AES加密算法

    引言在當今數字化時代,前端應用程序扮演著重要角色,用戶的敏感數據經常在前端進行加密和解密操作。然而,這樣的操作在網絡傳輸和存儲中可能會受到惡意攻擊的威脅。為了確保數據
  • 小紅書1周漲粉49W+,我總結了小白可以用的N條漲粉筆記

    作者:黃河懂運營一條性教育視頻,被54萬人&ldquo;珍藏&rdquo;是什么體驗?最近,情感博主@公主是用鮮花做的,火了!僅僅憑借一條視頻,光小紅書就有超過128萬人,為她瘋狂點贊!更瘋狂的是,這
  • 東方甄選單飛:有些鳥注定是關不住的

    文/彭寬鴻編輯/羅卿東方甄選創始人俞敏洪帶隊的&ldquo;7天甘肅行&rdquo;直播活動已在近日順利收官。成立后一年多時間里,東方甄選要脫離抖音自立門戶的傳聞不絕于耳,&ldquo;7
  • 三星電子Q2營收60萬億韓元 存儲業務營收同比仍下滑超過50%

    7月27日消息,據外媒報道,從三星電子所發布的財報來看,他們主要利潤來源的存儲芯片業務在今年二季度仍不樂觀,營收同比仍在大幅下滑,所在的設備解決方案
  • OPPO K11搭載長壽版100W超級閃充:26分鐘充滿100%

    據此前官方宣布,OPPO將于7月25日也就是今天下午14:30舉辦新品發布會,屆時全新的OPPO K11將正式與大家見面,將主打旗艦影像,和同檔位競品相比,其最大的賣
  • 聯想的ThinkBook Plus下一版曝光,鍵盤旁邊塞個平板

    ThinkBook Plus 是聯想的一個特殊筆記本類別,它在封面放入了一塊墨水屏,也給人留下了較為深刻的印象。據有人爆料,聯想的下一款 ThinkBook Plus 可能更特殊,它
  • 華為舉行春季智慧辦公新品發布會 首次推出電子墨水屏平板

    北京時間2月27日晚,華為在巴塞羅那舉行春季智慧辦公新品發布會,在海外市場推出之前已經在中國市場上市的筆記本、平板、激光打印機等辦公產品,并首次推出搭載
Top 主站蜘蛛池模板: 安阳县| 乳山市| 沙洋县| 舟山市| 林芝县| 德昌县| 汉川市| 尖扎县| 桂阳县| 华蓥市| 土默特左旗| 鄂托克前旗| 五河县| 那坡县| 孟村| 缙云县| 克山县| 信阳市| 临颍县| 广水市| 修武县| 三门峡市| 长寿区| 江城| 石阡县| 贡觉县| 来宾市| 孟州市| 阿鲁科尔沁旗| 孟连| 忻城县| 牙克石市| 吉林省| 景洪市| 浦城县| 壤塘县| 唐海县| 徐州市| 芒康县| 维西| 通道|