9
2020-01-20 16:02:44 +08:00 1
给你工具类:
```java
package com.utils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* 以静态变量保存 Spring ApplicationContext, 可在任何代码任何地方任何时候中取出 ApplicaitonContext.
*
*/
public class SpringContextHolder implements ApplicationContextAware {
private static ApplicationContext applicationContext;
/**
* 实现 ApplicationContextAware 接口的 context 注入函数, 将其存入静态变量.
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
// NOSONAR
SpringContextHolder.applicationContext = applicationContext;
}
/**
* 取得存储在静态变量中的 ApplicationContext.
*/
public static ApplicationContext getApplicationContext() {
checkApplicationContext();
return applicationContext;
}
/**
* 从静态变量 ApplicationContext 中取得 Bean, 自动转型为所赋值对象的类型.
*/
public static T getBean(String name) {
checkApplicationContext();
return (T) applicationContext.getBean(name);
}
/**
* 从静态变量 ApplicationContext 中取得 Bean, 自动转型为所赋值对象的类型.
*/
public static T getBean(Class clazz) {
checkApplicationContext();
return (T) applicationContext.getBean(clazz);
}
/**
* 清除 applicationContext 静态变量.
*/
public static void cleanApplicationContext() {
applicationContext = null;
}
private static void checkApplicationContext() {
if (applicationContext == null) {
throw new IllegalStateException(
"applicaitonContext 未注入,请在 applicationContext.xml 中定义 SpringContextHolder");
}
}
}
```