我们都知道@Value是不能用在静态属性上的,那么究竟Spring是怎么处理的呢?对此有什么解决方案?
构建自动装配的元数据
如下图,Spring会为加了一下注解的属性进行自动装配。
- @Autowired
- @Value

通过这里的代码可以看到,Spring是不会对静态属性进行自动装配的。但是Spring没有告诉我们,它为什么要跳过静态属性的自动装配,

同样,静态方法也不做自动装配。

如果我们必须要对静态属性赋值的时候,可以通过将@Value加到Method上来实现,只要这个方式不是静态的Spring就会对其进行自动装配。
Otherwise, @Autowired and @Value may not work on the configuration class itself, since it is possible to create it as a bean instance earlier than AutowiredAnnotationBeanPostProcessor.
摘自Spring官网的一句话。
Spring框架不会对静态属性进行@Autowired或@Value自动装配,这是由于Spring的设计选择。若需为静态属性赋值,可以使用非静态方法配合@Value注解。Spring官方文档建议避免在配置类上使用这些注解,因为配置类可能在AutowiredAnnotationBeanPostProcessor之前被实例化。
7136

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



