24.7. 类型安全的配置属性
使用@Value("${property}")
注解注入配置属性有时会比较麻烦(cumbersome),特别是需要使用多个properties,或数据本身有层次结构。Spring Boot提供一种使用配置的替代方法,这种方法允许强类型的beans以管理和校验应用的配置,例如:
@Component
@ConfigurationProperties(prefix="connection")
public class ConnectionSettings {
private String username;
private InetAddress remoteAddress;
// ... getters and setters
}
注 添加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
注解中列出要注册的属性类:
@Configuration
@EnableConfigurationProperties(ConnectionProperties.class)
public class MyConfiguration {
}
注 当@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
就可以不用了。
@Component
@ConfigurationProperties(prefix="connection")
public class ConnectionProperties {
// ... getters and setters
}
这种配置风格跟SpringApplication
的外部化YAML配置配合的很好:
# application.yml
connection:
username: admin
remoteAddress: 192.168.1.1
# additional configuration as required
为了使用@ConfigurationProperties
beans,你可以像使用其他bean那样注入它们:
@Service
public class MyService {
private final ConnectionProperties connection;
@Autowired
public MyService(ConnectionProperties connection) {
this.connection = connection;
}
//...
@PostConstruct
public void openConnection() {
Server server = new Server();
this.connection.configure(server);
}
}
注 使用@ConfigurationProperties
能够产生可被IDEs使用的元数据文件,具体参考Appendix B, Configuration meta-data。
此章节翻译的不好,后续整理*