spring bean標(biāo)注了Autowired注解的屬性沒(méi)有自動(dòng)注入對(duì)象問(wèn)題

1、問(wèn)題描述

某些spring 托管的bean,被標(biāo)注Autowired注解的屬性,沒(méi)有自動(dòng)注入對(duì)象。比如下面這個(gè)類(lèi)。


/**

* Created by zhengwei on 2017/6/21.

*/

@Component

public classGetProductByProductIdRequestHandlerextendsPcRequestHandler {

@Autowired

privateProductQueryManagerproductQueryManager;

@Override

protectedGetProductByProductIdResponsedoHandle(GetProductByProductIdRequest request) {

GetProductByProductIdResponse response =newGetProductByProductIdResponse();

ProductDO product;

try{

product =this.productQueryManager.getProductBaseInfoById(request.getProductId());

}catch(Exception e) {

logger.error("getProductBaseInfoById error, productId="+ request.getProductId(),e);

response.setSuccess(false);

response.setResultCode(BizErrorCode.COMMON_ERROR.getErrorCode());

response.setResultMsg(BizErrorCode.COMMON_ERROR.getErrorMsg());

returnresponse;

}

response.setProduct(product);

response.setSuccess(true);

returnresponse;

}

@Override

publicClasssupportRequest() {

returnGetProductByProductIdRequest.class;

}

}

運(yùn)行的過(guò)程中,上圖GetProductByProductIdRequestHandler中的屬性productQueryManager為null,導(dǎo)致空指針異常。

2、問(wèn)題產(chǎn)生原因

項(xiàng)目啟用了配置中心,通過(guò)PropertyPlaceholderConfigurer實(shí)現(xiàn),因此它是個(gè)BeanFactoryPostProcessor,而此bean在初始化spring時(shí),會(huì)去配置中心獲取配置項(xiàng)到本地內(nèi)存,其中該bean初始化過(guò)程中,有這么一段代碼,如下圖:


private void initListener(PropertiesConfiguration config) {

Map listeners = applicationContext.getBeansOfType(MessageConfCenterListener.class);

if (listeners == null) {

listeners = new HashMap();

}

// add default contextPropertiesListener

listeners.put("contextPropertiesListener", new MessageConfCenterListener() {

@Override

public void notifyEvent(ConfigurationEvent event) {

switch (event.getType()) {

case ADD:

case UPDATE:

contextProperties.put(event.getPropertyName(), event.getPropertyValue());

break;

case CLEAR:

contextProperties.remove(event.getPropertyName());

}

}

});

config.addConfigurationListener(new MessageConfigurationListener(listeners.values()));

}

可以看到其中第2行代碼是,

Map listeners = applicationContext.getBeansOfType(MessageConfCenterListener.class);

也就是從applicationContext獲取MessageConfCenterListener,getBeansOfType此方法是根據(jù)name遍歷整個(gè)bean factory里的bean,如果是FactoryBean的話(huà),會(huì)先創(chuàng)建此bean,問(wèn)題就出在這里了。這里需要看看AbstractApplicationContext里的refresh方法,如下圖:


@Override

public void refresh() throws BeansException, IllegalStateException {

synchronized (this.startupShutdownMonitor) {

// Prepare this context for refreshing.

prepareRefresh();

// Tell the subclass to refresh the internal bean factory.

ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

// Prepare the bean factory for use in this context.

prepareBeanFactory(beanFactory);

try {

// Allows post-processing of the bean factory in context subclasses.

postProcessBeanFactory(beanFactory);

// Invoke factory processors registered as beans in the context.

invokeBeanFactoryPostProcessors(beanFactory);

// Register bean processors that intercept bean creation.

registerBeanPostProcessors(beanFactory);

// Initialize message source for this context.

initMessageSource();

// Initialize event multicaster for this context.

initApplicationEventMulticaster();

// Initialize other special beans in specific context subclasses.

onRefresh();

// Check for listener beans and register them.

registerListeners();

// Instantiate all remaining (non-lazy-init) singletons.

finishBeanFactoryInitialization(beanFactory);

// Last step: publish corresponding event.

finishRefresh();

}

catch (BeansException ex) {

if (logger.isWarnEnabled()) {

logger.warn("Exception encountered during context initialization - " +

"cancelling refresh attempt: " + ex);

}

// Destroy already created singletons to avoid dangling resources.

destroyBeans();

// Reset 'active' flag.

cancelRefresh(ex);

// Propagate exception to caller.

throw ex;

}

finally {

// Reset common introspection caches in Spring's core, since we

// might not ever need metadata for singleton beans anymore...

resetCommonCaches();

}

}

}

1、prepareBeanFactory(beanFactory)方法,表示準(zhǔn)備動(dòng)作,初始化一些默認(rèn)的配置。

2、invokeBeanFactoryPostProcessors(beanFactory),執(zhí)行BeanFactoryPostProcessor,而我們的配置中心是通過(guò)PropertyPlaceholderConfigurer來(lái)實(shí)現(xiàn)的,而PropertyPlaceholderConfigurer是一個(gè)BeanFactoryPostProcessor,因此這個(gè)時(shí)候會(huì)被執(zhí)行。

3、registerBeanPostProcessors(beanFactory),注冊(cè)BeanPostProcessor,這個(gè)BeanPostProcessor干啥的呢,spring的Autowired注解就是通過(guò)AutowiredAnnotationBeanPostProcessor來(lái)實(shí)現(xiàn)的。

因此當(dāng)執(zhí)行BeanFactoryPostProcessor的時(shí)候,spring還沒(méi)有往容器里注冊(cè)AutowiredAnnotationBeanPostProcessor,問(wèn)題就這么發(fā)生了。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,662評(píng)論 19 139
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,282評(píng)論 6 342
  • 文章作者:Tyan博客:noahsnail.com | CSDN | 簡(jiǎn)書(shū) 3.9 Annotation-base...
    SnailTyan閱讀 1,280評(píng)論 0 3
  • 注意LifecycleProcessor接口繼承了Lifcycle接口。同時(shí),增加了2個(gè)方法,用于處理容器的ref...
    google666s閱讀 1,187評(píng)論 0 51
  • 什么是Spring Spring是一個(gè)開(kāi)源的Java EE開(kāi)發(fā)框架。Spring框架的核心功能可以應(yīng)用在任何Jav...
    jemmm閱讀 16,779評(píng)論 1 133

友情鏈接更多精彩內(nèi)容