设为首页 加入收藏

TOP

深入Spring Boot:那些注入不了的 Spring 占位符 ( ${} 表达式 )(三)
2017-12-31 06:06:57 】 浏览:683
Tags:深入 Spring Boot 那些 注入 不了 占位 表达式
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}”)
首页 上一页 1 2 3 下一页 尾页 3/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇分布式实时日志分析解决方案 ELK .. 下一篇IDEA 代码生成插件 CodeMaker

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目