通過ApplicationContextAware載入Spring上下文環境
阿新 • • 發佈:2019-01-25
在程式中每一次使用new ClassPathXmlApplicationContext時都會重新裝載配置檔案並例項化上下文bean。此時如果某些執行緒類也配置在該檔案中,那麼會造成做相同工作的執行緒被啟動多次(包括web容器初始化時啟動的以及new ClasspathXmlApplicationContext時啟動的執行緒)。為了避免這種情況就需要用到ApplicationContextAware,通過它Spring容器會自動呼叫ApplicationContextAware介面中的setApplicationContext方法將把上下文環境物件注入進去。
我們在ApplicationContextAware的實現類中,就可以通過這個上下文環境物件得到Spring容器中的Bean。
具體如下:
1.實現ApplicationContextAware介面:
- package com.bis.majian.practice.module.spring.util;
- import org.springframework.beans.BeansException;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.ApplicationContextAware;
-
publicclass SpringContextHelper implements
- privatestatic ApplicationContext context = null;
- @Override
- publicvoid setApplicationContext(ApplicationContext applicationContext)
- throws BeansException {
- this.context = applicationContext;
- }
-
publicstatic Object getBean(String name){
- return context.getBean(name);
- }
- }
2.在Spring的配置檔案中配置這個類,Spring容器會在載入完Spring容器後把上下文物件呼叫這個物件中的setApplicationContext方法:
- <?xmlversion="1.0"encoding="UTF-8"?>
- <beansxmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:tx="http://www.springframework.org/schema/tx"
- xmlns:context="http://www.springframework.org/schema/context"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://www.springframework.org/schema/tx
- http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd" default-autowire="byName">
- <beanid="springContextHelper"class="com.bis.majian.practice.module.spring.util.SpringContextHelper"></bean>
- <context:component-scanbase-package="com.bis.majian.practice.module.*"/>
- </beans>
3.在web專案中的web.xml中配置載入Spring容器的Listener:
- <!-- 初始化Spring容器,讓Spring容器隨Web應用的啟動而自動啟動 -->
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
4.在專案中即可通過這個SpringContextHelper呼叫getBean()方法得到Spring容器中的物件了。