24.7. 类型安全的配置属性

使用@Value("${property}")注解注入配置属性有时会比较麻烦(cumbersome),特别是需要使用多个properties,或数据本身有层次结构。Spring Boot提供一种使用配置的替代方法,这种方法允许强类型的beans以管理和校验应用的配置,例如:

  1. @Component
  2. @ConfigurationProperties(prefix="connection")
  3. public class ConnectionSettings {
  4. private String username;
  5. private InetAddress remoteAddress;
  6. // ... getters and setters
  7. }

添加setter和getter是相当正确的,因为绑定是通过标准的Java Beans属性描述符进行的,跟Spring MVC一样,对于不可变类型或从String强制转换的也一样。只要它们初始化了,maps,collections,arrays只需要getter,setter不是必须的,因为绑定者(binder)能够改变它们。如果有setter,maps,collections,arrays就能够被创建。Maps和collections可以仅通过getter进行扩展,而arrays需要setter。嵌套的POJO属性只能通过默认的构造器,或接收一个单一的能够转换为string的值的构造器。有些人使用Project Lombok自动添加getters和setters。

查看@Value和@ConfigurationProperties之间的区别。

你需要在@EnableConfigurationProperties注解中列出要注册的属性类:

  1. @Configuration
  2. @EnableConfigurationProperties(ConnectionProperties.class)
  3. public class MyConfiguration {
  4. }

@ConfigurationProperties bean以这种方式注册时,该bean将有个约定的名称:<prefix>-<fqn><prefix>@ConfigurationProperties注解中定义的environment key前缀,<fqn>是bean的全限定名。如果注解中没有提供任何前缀,那就只使用bean的全限定名。上述示例中的bean名称将是connection-com.example.ConnectionProperties,假定ConnectionProperties位于com.example包下。

尽管上述配置为ConnectionProperties创建了一个常规的bean,不过我们建议@ConfigurationProperties只用来处理environment(只用于注入配置,系统环境之类的),特别是不要注入上下文中的其他beans。话虽如此,@EnableConfigurationProperties注解会自动应用到你的项目,任何存在的,注解@ConfigurationProperties的bean将会从Environment属性中得到配置。只要确定ConnectionProperties是一个已存在的bean,MyConfiguration就可以不用了。

  1. @Component
  2. @ConfigurationProperties(prefix="connection")
  3. public class ConnectionProperties {
  4. // ... getters and setters
  5. }

这种配置风格跟SpringApplication的外部化YAML配置配合的很好:

  1. # application.yml
  2. connection:
  3. username: admin
  4. remoteAddress: 192.168.1.1
  5. # additional configuration as required

为了使用@ConfigurationProperties beans,你可以像使用其他bean那样注入它们:

  1. @Service
  2. public class MyService {
  3. private final ConnectionProperties connection;
  4. @Autowired
  5. public MyService(ConnectionProperties connection) {
  6. this.connection = connection;
  7. }
  8. //...
  9. @PostConstruct
  10. public void openConnection() {
  11. Server server = new Server();
  12. this.connection.configure(server);
  13. }
  14. }

使用@ConfigurationProperties能够产生可被IDEs使用的元数据文件,具体参考Appendix B, Configuration meta-data

此章节翻译的不好,后续整理*