@Component
@SuppressWarnings("all")
public class SpringContextHolder implements ApplicationContextAware {
private static ApplicationContext applicationContext;
/**
* 实现ApplicationContextAware接口的context注入函数, 将其存入静态变量.
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
if (SpringContextHolder.applicationContext == null) {
SpringContextHolder.applicationContext = applicationContext; // NOSONAR
}
}
/**
* 取得存储在静态变量中的ApplicationContext.
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) {
return (T) applicationContext.getBean(name);
}
/**
* 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(Class<T> clazz) {
return (T) applicationContext.getBeansOfType(clazz);
}
/**
* 清除applicationContext静态变量.
*/
public static void cleanApplicationContext() {
applicationContext = null;
}
}
当有类实现ApplicationContextAware接口时,必须先在类里面进行一次app的实例化,
否则Spring回调setApplicationContext方法,此时,Spring还未实例化app实例,自然不能吧app实例注入进该工具类中的applicationContext对象,会报空指针
static {
String xmlPath = "****.xml";
ApplicationContext app = new ClassPathXmlApplicationContext(xmlPath);
}
只需要在工具类中进行实例化一次,后面就可以通过Spring进行自动注入