前几天写web项目的时候,用到了spring mvc。
但是又写bean。我要在代码里面生成,而这个bean里面,又有一些属性是通过spring注入的。
所以,只能通过ApplicationContext来获取。
在servlet里面获取ApplicationContext其实可以通过spring提供的方法:
| 1 | WebApplicationContextUtils.getWebApplicationContext(ServletContext) | 
来获取。
这个方法前提是要在web.xml里面即一个listener:
| 1 2 3 4 5 6 7 8 9 10 | <context-param>        <param-name>contextConfigLocation</param-name>        <param-value>            classpath:spring-servlet.xml,            classpath:applicationContext.xml        </param-value>    </context-param><listener>        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>    </listener> | 
不过这样子只能在servlet里面获取。
如果要在servlet外获取ApplicationContext呢?
其实可以封装一下的:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | packageme.idashu.code.util;importorg.springframework.context.ApplicationContext;importorg.springframework.web.context.WebApplicationContext;importorg.springframework.web.context.support.WebApplicationContextUtils;importjavax.servlet.ServletContextEvent;importjavax.servlet.ServletContextListener;/** * 描述:ApplicationContext容器 * * @author: dashu * @since: 13-5-11 */publicclassAppContext implementsServletContextListener {    privatestaticWebApplicationContext springContext;    publicAppContext() {        super();    }    publicvoidcontextInitialized(ServletContextEvent event) {        springContext = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());    }    publicvoidcontextDestroyed(ServletContextEvent event) {    }    publicstaticApplicationContext getApplicationContext() {        returnspringContext;    }} | 
还需要在web.xml里面再加条记录:
| 1 2 3 | <listener>        <listener-class>me.idashu.code.util.AppContext</listener-class>    </listener> | 
其实就是在content初始化的时候,把ApplicationContext保存起来,下次方便调用。
spring中获取applicationContext(2),布布扣,bubuko.com
spring中获取applicationContext(2)
原文地址:http://www.cnblogs.com/peijie-tech/p/3824971.html