import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
@Component
@Lazy(false)
public class SpringUtil implements ApplicationContextAware, DisposableBean {
private static final Logger logger = LoggerFactory.getLogger(SpringUtil.class);
private static ApplicationContext applicationContext = null;
public SpringUtil() {
}
public static ApplicationContext getApplicationContext() {
assertContextInjected();
return applicationContext;
}
public void setApplicationContext(ApplicationContext applicationContext) {
logger.debug("SpringUtil:{}", applicationContext);
if (SpringUtil.applicationContext != null) {
logger.info("SpringUtil中的ApplicationContext被覆盖, 原有ApplicationContext为:" + SpringUtil.applicationContext);
}
SpringUtil.applicationContext = applicationContext;
}
public static <T> T getBean(String name) {
assertContextInjected();
return (T) applicationContext.getBean(name);
}
public static <T> T getBean(Class<T> requiredType) {
assertContextInjected();
return applicationContext.getBean(requiredType);
}
public static String getBeanNamesForType(Class thisClass) {
assertContextInjected();
return applicationContext.getBeanNamesForType(thisClass)[0];
}
private static void clearHolder() {
if (logger.isDebugEnabled()) {
logger.debug("清除SpringUtil中的ApplicationContext:" + applicationContext);
}
applicationContext = null;
}
private static void assertContextInjected() {
Assert.notNull(applicationContext, "applicationContext属性未注入, 请在applicationContext.xml中定义SpringContextHolder.");
}
public void destroy() throws Exception {
clearHolder();
}
}
SpringUtil工具类
最新推荐文章于 2024-02-16 21:14:19 发布