写在前面:
我是「境里婆娑」。我还是从前那个少年,没有一丝丝改变,时间只不过是考验,种在心中信念丝毫未减,眼前这个少年,还是最初那张脸,面前再多艰险不退却。
写博客的目的就是分享给大家一起学习交流,如果您对 Java感兴趣,可以关注我,我们一起学习
前言:前两天在做项目时候,一个需求是要求两个bean启动要互斥,后来经过一番查找发现SpringBoot这个注解@ConfigurationProperties可以实现此功能。经过一番学习来分享给大家。
一、@ConfigurationProperties介绍
@ConditionalOnProperty一个最大的好处是可以控制@Configuration是否生效。
@ConditionalOnProperty属性介绍:
String[] value() default {}; //数组,获取对应property名称的值,与name不可同时使用
String prefix() default "";//property名称的前缀,可有可无
String[] name() default {};//数组,property完整名称或部分名称(可与prefix组合使用,组成完整的property名称),与value不可同时使用
String havingValue() default "";//可与name组合使用,比较获取到的属性值与havingValue给定的值是否相同,相同才加载配置
boolean matchIfMissing() default false;//缺少该property时是否可以加载。如果为true,没有该property也会正常加载;反之报错
@ConditionalOnProperty如何控制@Configuration是否生效,具体操作是通过其两个属性name以及havingValue来实现的。
name | havingValue |
---|---|
true | true |
false | false |
true | false |
false | true |
name和havingValue属性相同的时候@Configuration生效,否则不生效。
一、@ConfigurationProperties使用详情
1、在application.properties添加配置文件
myapp.mail.localPath=zsl
myapp.mail.enable=true
2、创建两个配置类
Conditional1Configuration配置类
@Configuration
@ConfigurationProperties(prefix = "myapp.mail")
@ConditionalOnProperty(prefix = "myapp.mail",name = "enable",havingValue = "false")
public class Conditional1Configuration {
private String localPath;
private Boolean enable;
@Bean
public Conditional1 test1() {
Conditional1 test = new Conditional1();
test.setEnable(enable);
test.setUser(localPath);
return test;
}
public String getLocalPath() {
return localPath;
}
public void setLocalPath(String localPath) {
this.localPath = localPath;
}
public Boolean getEnable() {
return enable;
}
public void setEnable(Boolean enable) {
this.enable = enable;
}
}
ConditionalConfiguration配置类
@Configuration
@ConfigurationProperties(prefix = "myapp1.mail")
@ConditionalOnProperty(prefix = "myapp.mail",name = "enable",havingValue = "true",matchIfMissing = true)
public class ConditionalConfiguration {
@Value("${myapp.mail.enable}")
private Boolean enable;
private String localPath;
@Bean
public Conditional test2() {
Conditional test = new Conditional();
test.setEnable(enable);
test.setUser(localPath);
return test;
}
public Boolean getEnable() {
return enable;
}
public void setEnable(Boolean enable) {
this.enable = enable;
}
public String getLocalPath() {
return localPath;
}
public void setLocalPath(String localPath) {
this.localPath = localPath;
}
}
当我把配置文件myapp.mail.enable改为true时候这个配置ConditionalConfiguration启动,当改为false时候 Conditional1Configuration启动。
至此,我们怎么使用注解@ConfigurationProperties介绍完毕。
如果想更详细查看以上所有代码请移步到github:如何使用注解@ConfigurationProperties