通过监听器 获取Spring加载后的applicationContext
最近遇到的是这样一个问题:
需要在Spring完成加载之后,获取到Spring管理的 ApplicationContext。
上网查了几个方法,大家都说实现接口ApplicationContextAware
实现该接口的setApplicationContext(ApplicationContext context)方法,并保存ApplicationContext 对象。Spring初始化时,会通过该方法将ApplicationContext 对象注入。
但是实际操作中遇到了问题,配置了这个类,也加了SpringBean的配置,但是启动的时候,Spring没有帮我注入这个对象,我也不太明白为什么,希望有明白的大神们讲解一下。
PS:问题解决,参考http://kewen1989.iteye.com/blog/1893994于是我就用了这样一个方法实现:
还是实现了这样一个接口:
public class GetContext implements ServletContextListener{ private static WebApplicationContext webApplicationContext; private static ApplicationContextHelper helper = new ApplicationContextHelper(); @Override public void contextDestroyed(ServletContextEvent arg0) { } @Override public void contextInitialized(ServletContextEvent arg0) { webApplicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(arg0.getServletContext()); helper.setApplicationContext(webApplicationContext); }这样我们就可以在别的地方调用ApplicationContextHelper的getContext()方法,获取到需要的ApplicationContext对象了