问题
今天在玩的过程中发现用@Autowired注解了类属性,属性使用了static关键字,编译正常,但是运行过程中发现此属性的值是null,没有自动装配成功。
@Autowired
private static Environment environment;
原因
所以,在Springframework里,我们是不能@Autowired一个静态变量,使之成为一个Spring bean的。为什么?其实很简单,因为当类加载器加载静态变量时,Spring上下文尚未加载。所以类加载器不会在bean中正确注入静态类,并且会失败。
解决方案
给静态组件加setter方法,并在这个方法上加上@Autowired。Spring能扫描到AutowiredTypeComponent的bean,然后通过setter方法注入。示例如下:
@Configuration
@ComponentScan
@PropertySource("PropertySource/test.properties")
public class Config {
private static Environment environment;
@Autowired
public void setEnvironment(Environment environment) {
this.environment = environment;
}
public void getName() throws UnsupportedEncodingException {
String str = environment.getProperty("name");
System.out.println(str);
}
}