Update 23.7. Typesafe Configuration Properties.md
parent
bedfeb745c
commit
c231181f30
|
@ -0,0 +1,44 @@
|
|||
### 23.7. 类型安全的配置属性
|
||||
|
||||
使用@Value("${property}")注解注入配置属性有时可能比较笨重,特别是需要使用多个properties或你的数据本身有层次结构。为了控制和校验你的应用配置,Spring Boot提供一个允许强类型beans的替代方法来使用properties。
|
||||
|
||||
示例:
|
||||
```java
|
||||
@Component
|
||||
@ConfigurationProperties(prefix="connection")
|
||||
public class ConnectionSettings {
|
||||
private String username;
|
||||
private InetAddress remoteAddress;
|
||||
// ... getters and setters
|
||||
}
|
||||
```
|
||||
当@EnableConfigurationProperties注解应用到你的@Configuration时,任何被@ConfigurationProperties注解的beans将自动被Environment属性配置。这种风格的配置特别适合与SpringApplication的外部YAML配置进行配合使用。
|
||||
```json
|
||||
# application.yml
|
||||
connection:
|
||||
username: admin
|
||||
remoteAddress: 192.168.1.1
|
||||
# additional configuration as required
|
||||
```
|
||||
为了使用@ConfigurationProperties beans,你可以使用与其他任何bean相同的方式注入它们。
|
||||
```java
|
||||
@Service
|
||||
public class MyService {
|
||||
@Autowired
|
||||
private ConnectionSettings connection;
|
||||
//...
|
||||
@PostConstruct
|
||||
public void openConnection() {
|
||||
Server server = new Server();
|
||||
this.connection.configure(server);
|
||||
}
|
||||
}
|
||||
```
|
||||
你可以通过在@EnableConfigurationProperties注解中直接简单的列出属性类来快捷的注册@ConfigurationProperties bean的定义。
|
||||
```java
|
||||
@Configuration
|
||||
@EnableConfigurationProperties(ConnectionSettings.class)
|
||||
public class MyConfiguration {
|
||||
}
|
||||
```
|
||||
**注**:使用@ConfigurationProperties能够产生可被IDEs使用的元数据文件。具体参考[Appendix B, Configuration meta-data](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#configuration-metadata)。
|
Loading…
Reference in New Issue