细心的朋友已经发现,每当我们在一个静态static方法中引用Spring的注入bean的时候,会报错:
告诉我们,不能再一个静态方法中引用一个非静态的变量。
我们可以定义一个通用的获取context中bean的静态方法,来解决例如此刻的引入。
import org.apache.commons.lang3.Validate;
import org.springframework.beans.BeansException;
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;
@Component
@Lazy(false) //禁止懒加载
public class SpringContextHolder implements ApplicationContextAware, DisposableBean {
private static ApplicationContext context = null;
//实现ApplicationContext接口的注入ApplicationContext方法
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
public static ApplicationContext getApplicationContext(){
checkApplicationContext();
return context;
}
//根据beanName获取bean
public static <T> T getBean(String beanName){
checkApplicationContext();
return (T) context.getBean(beanName);
}
//根据bean Class 来获取bean
public static <T> T getBean(Class beanClass){
checkApplicationContext();
return (T) context.getBean(beanClass);
}
//实现DisposableBean的destory方法,容器销毁,清除Context
public void destroy() throws Exception {
context = null;
}
//校验ApplicationContext是否存在
private static void checkApplicationContext() {
Validate.validState(null != context, "ApplicationContext未注入,请检查");
}
}
在静态static 方法中的引用方式:
public class TestSpringContextHolder {
@Autowired
private UserService userService;
public static void main(String[] args) {
AnnotationConfigApplicationContext configApplicationContext =
new AnnotationConfigApplicationContext(HolerConfig.class);
UserService userService = SpringContextHolder.getBean("userService");
System.out.println("通过SpringContextHolder获取bean: ");
userService.test();
}
}