我们都知道@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官网的一句话。