package com.jc.system.common.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.DisposableBean; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; @Component public class SpringContextHolder implements ApplicationContextAware, DisposableBean { private static ApplicationContext applicationContext = null; private static Logger logger = LoggerFactory .getLogger(SpringContextHolder.class); public static ApplicationContext getApplicationContext() { return applicationContext; } @SuppressWarnings("unchecked") public static <T> T getBean(String name) { return (T) applicationContext.getBean(name); } public static <T> T getBean(Class<T> requiredType) { return applicationContext.getBean(requiredType); } public static void clearHolder() { logger.debug("清除SpringContextHolder中的ApplicationContext:" + applicationContext); applicationContext = null; } @Override public void setApplicationContext(ApplicationContext applicationContext) { if (SpringContextHolder.applicationContext != null) { logger.warn("SpringContextHolder中的ApplicationContext被覆盖, 原有ApplicationContext为:" + SpringContextHolder.applicationContext); } SpringContextHolder.applicationContext = applicationContext; // NOSONAR } @Override public void destroy() throws Exception { SpringContextHolder.clearHolder(); } }
实现Spring ApplicationContextAware接口与DisposableBean接口,实现特殊注入
猜你喜欢
转载自aa80303857.iteye.com/blog/2351596
今日推荐
周排行