Bean是在创建对象时加载依赖的,而静态变量是属于类属性,是优先于对象属性加载的,因此Bean是无法注入静态变量的,被标记的静态变量值为null,当然也无法在静态方法中使用Bean对象。
如果要在静态方法中使用Bean对象,那么需要将加载完成的Bean手动赋值给静态变量再通过静态变量来使用。
假设现有两个类A、B,A被标记为Bean了,现在要在B的静态方法中使用依赖注入的A对象。基于之前的思路有如下三种方式:
方法1:使用@PostConstruct
@Component
public class B {
private A a;
private static B b;
@Autowired
public B(A a) {
this.a = a;
}
@PostConstruct
public void init() {
b = this;
b.a = this.a;
}
public static void print() {
b.a.print();
}
}
方法2:
@Component
public class B {
private static A a;
@Autowired
public B(A a) {
B.a = a;
}
public static void print() {
a.print();
}
}
方法3:通过上下文来获取Bean对象
@Component
public class BeanUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
BeanUtils.applicationContext = applicationContext;
}
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) throws BeansException {
if (applicationContext == null){
return null;
}
return (T) applicationContext.getBean(name);
}
}
@Component
public class B {
public static void print() {
A a = BeanUtils.getBean("a");
a.print();
}
}
静态方法无法直接注入Bean,因为Bean加载晚于静态变量。要使用Bean,可以手动赋值给静态变量,或者通过@PostConstruct、上下文获取Bean对象。文章介绍了在静态方法中使用依赖注入的Bean对象的三种方法。
967

被折叠的 条评论
为什么被折叠?



