文章字数:624,阅读全文大约需要2分钟
Spring
提供的自动将application.properties
配置文件中参数绑定到指定类成员变量的注解,功能上类似@Value
基本使用
- 配置参数
1 2
| myapp.mail.enable=true myapp.mail.default-subject=test subject
|
- 绑定配置到配置类
1 2 3 4 5 6 7 8 9 10 11 12
| @Data
@ConfigurationProperties(prefix = "myapp.mail") public class MailProperties { private Boolean enable = Boolean.TRUE; private String defaultSubject; }
|
参数绑定规则
- 宽松绑定规则
relaxed binding
,多种书写方式都可以绑定
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| myapp.mail.defaultSubject=test subject myapp.mail.defaultsubject=test subject myapp.mail.default-subject=test subject myapp.mail.default_subject=test subject myapp.mail.DEFAULT-SUBJECT=test subject ```
2. 前缀必须相同 3. 类型必须是可转换的,不可转换时默认抛出异常。设置`ignoreInvalidFields=true`可以忽略此错误 4. 未绑定的配置参数默认忽略,如果想存在未绑定参数是报错可以设置`ignoreUnknownFields=false` 5. 参数是否有效校验
```java // 开启参数校验 @Validated @Data @ConfigurationProperties(prefix = "myapp.mail") public class MailProperties { /** 设置校验规则 */ @NotNull private Boolean enable = Boolean.TRUE; @NotEmpty private String defaultSubject; }
|
激活配置
- 创建了一个
@ConfigurationProperties
注解的配置类,还需要将其添加到应用上下文才能使用
- 可以直接
@Componment
将其添加到容器中
- 使用
@configuration
类中声明也有同样效果,和2类似,都是注册成bean
- 使用
@EnableConfigurationProperties
注解,让当前类被Spring
容器感知
复杂类型属性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| private List<String> smtpServer;
private Map<String, String> serverInfo;
@DurationUnit(ChronoUnit.SECONDS) private Duration mails;
@DataSizeUnit(DataUnit.MEGABYTES) private DataSize maxAttachementSize = DataSize.ofMegabytes(2);
|
1 2 3 4 5 6 7 8 9 10 11 12 13
| myapp.mail.smtpServerp[0]=server0 myapp.mail.smtpServerp[1]=server1
# yml本身支持list myapp: mail: smtp-servers: - server0 - server1
# 可以指定单位,不指定按照默认单位 myapp.mail.mails=2s myapp.mail.maxAttachementSize=1m
|
自定义类型
1 2
| /** 声明属性 */ private Weight weight;
|
1 2 3 4 5 6 7
| public class WeightConverter implements Converter<String, String> {
@Override public Weight conver(String source) { } }
|
1 2 3 4 5 6 7 8 9
| @Configuration class PropertiesConfig { @Bean @ConfigurationPropertiesBinding public WeightConverter weightConverter() { return new WeightConverter(); } }
|
配置自动补全
1 2 3 4 5
| <dependency> <groupId>com.springframwork.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
|
- 重新
build
项目,configuration processor
会自动生成一个spring-configuration-metadata.json
application.properties
中写配置就会自动提示
- 标记属性为
deprecated
标记原因和替代属性,并重新build
1 2 3 4 5
| @DeprecatedConfigurationProperty(reason="change name", replacement = "none") public String getDefaultSubject() { }
|