ader);
result = beanFactory.getBeanNamesForAnnotation(typeClass);
- beanFactory.getBeanNamesForAnnotation 会导致FactoryBean提前初始化,创建出javaVersion里,传入的${java.version.key}没有被处理,值为null。
- spring boot 1.4.5 修复了这个问题:https://github.com/spring-projects/spring-boot/issues/8269
实现spring boot starter要注意不能导致bean提前初始化
用户在实现spring boot starter时,通常会实现Spring的一些接口,比如BeanFactoryPostProcessor接口,在处理时,要注意不能调用类似beanFactory.getBeansOfType,beanFactory.getBeanNamesForAnnotation 这些函数,因为会导致一些bean提前初始化。
而上面有提到PropertySourcesPlaceholderConfigurer的order是最低优先级的,所以用户自己实现的BeanFactoryPostProcessor接口在被回调时很有可能占位符还没有被处理。
对于用户自己定义的@ConfigurationProperties对象的注入,可以用类似下面的代码:
@ConfigurationProperties(prefix = "spring.my")
public class MyProperties {
String key;
}
public static MyProperties buildMyProperties(ConfigurableEnvironment environment) {
MyProperties myProperties = new MyProperties();
if (environment != null) {
MutablePropertySources propertySources = environment.getPropertySources();
new RelaxedDataBinder(myProperties, "spring.my").bind(new PropertySourcesPropertyValues(propertySources));
}
return myProperties;
}
总结
- 占位符(${}表达式)是在PropertySourcesPlaceholderConfigurer里处理的,也就是BeanFactoryPostProcessor接口
- spring的生命周期是比较复杂的事情,在实现了一些早期的接口时要小心,不能导致spring bean提前初始化
- 在早期的接口实现里,如果想要处理占位符,可以利用spring自身的api,比如 environment.resolvePlaceholders(“${db.user}”)