分类: Java
2015-08-25 11:32:55
点击(此处)折叠或打开
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.ApplicationContextAware;
- import org.springframework.web.context.ContextLoaderListener;
- import org.springframework.web.context.WebApplicationContext;
- import org.springframework.web.servlet.DispatcherServlet;
- public class ContextListener extends ContextLoaderListener implements ApplicationContextAware {
- private static final Logger log = LoggerFactory.getLogger(ContextListener.class);
- private static final String ATTR_NAME = "org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcherServlet";
- private static ApplicationContext applicationContext;
- private static WebApplicationContext webApplicationContext;
- public static <T> T getBean(Class<T> tClass) {
- if (webApplicationContext == null) {
- webApplicationContext = (WebApplicationContext) getCurrentWebApplicationContext()
- .getServletContext().getAttribute(ATTR_NAME);
- }
- if (webApplicationContext != null) {
- T bean = webApplicationContext.getBean(tClass);
- if (bean != null) {
- return bean;
- }
- }
- if (applicationContext != null) {
- return applicationContext.getBean(tClass);
- }
- return null;
- }
- @Override
- public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
- ContextListener.applicationContext = applicationContext;
- }
- }