1.创建MyContextLoaderListener
继承ContextLoaderListener,重写contextInitialized方法
ServletContextListener是对ServeltContext的一个监听.servelt容器启动,serveltContextListener就会调用contextInitialized方法.在方法里面调用event.getServletContext()可以获取ServletContext,ServeltContext是一个上下文对象,他的数据供所有的应用程序共享,进行一些业务的初始化servelt容器关闭,serveltContextListener就会调用contextDestroyed.
import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import org.springframework.context.ApplicationContext; import org.springframework.web.context.ContextLoaderListener; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils;
public class MyContextLoaderListener extends ContextLoaderListener { private static ApplicationContext context; public static ApplicationContext getApplicationContext() { return context; } /* * (non-Javadoc) * * @see * org.springframework.web.context.ContextLoaderListener#contextInitialized * (javax.servlet.ServletContextEvent) */ @Override public void contextInitialized(ServletContextEvent event) { super.contextInitialized(event); ServletContext servletContext = event.getServletContext(); WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext); context = applicationContext; } @Override public void contextDestroyed(ServletContextEvent event) { super.contextDestroyed(event); } }
2.创建SpringContext
import org.springframework.context.ApplicationContext; import xxx.xxx.MyContextLoaderListener; public class SpringContext { @SuppressWarnings("unchecked") public static <T> T getBean(String name) { ApplicationContext context = IHomeContextLoaderListener.getApplicationContext(); if (context == null) { return null; } return (T) context.getBean(name); } public static <T> T getBean(String name, Class<T> classsz) { ApplicationContext context = IHomeContextLoaderListener.getApplicationContext(); if (context == null) { return null; } return (T) context.getBean(name, classsz); } public static <T> T getBean(Class<T> classsz) { ApplicationContext context = IHomeContextLoaderListener.getApplicationContext(); if (context == null) { return null; } return (T) context.getBean(classsz); } }
3.修改web.xml
<listener> <listener-class>xxx.xxx.MyServletContextListener</listener-class> </listener>
4.获取Spring Bean
SpringContext.get(xxx.class)
原文:https://www.cnblogs.com/acelly/p/10407211.html