配置Spring Boot通过@ConditionalOnProperty来控制Configuration是否生效
qny: AccessKey: 123 SecretKey: 123 bucket: aaa enable:true
一般动态配置我们会用@value注解或者实现InitializingBean,这里我用的是七牛云的举例,为了解耦合动态的去管理配置文件生效
@Data
@ConfigurationProperties(prefix=”qny”)
public class QnyProperties {
private String AccessKey;
private String SecretKey;
private String bucket;
}
我这里用@ConfigurationProperties(prefix=”qny”) 读取配置文件以前缀为qny去注入,但是还没有交由spring 进行管理配置没有生效
在这里用@EnableConfigurationProperties交由Spring容器通过配置文件去创建QnyProperties
@RequiredArgsConstructor
@EnableConfigurationProperties({QnyProperties.class})
@org.springframework.context.annotation.Configuration
public class QnyAutoConfiguration {
public final QnyProperties qnyProperties;
@Bean
@ConditionalOnMissingBean(QnyProperties.class)
@ConditionalOnProperty(name = "qny.enable", havingValue = "true", matchIfMissing = true)
public Configuration configuration(){
return new Configuration(Region.region0());
}
@Bean
@ConditionalOnProperty(name = "qny.enable", havingValue = "true", matchIfMissing = true)
public UploadManager uploadManager(Configuration configuration){
return new UploadManager(configuration);
}
@Bean
@ConditionalOnMissingBean(QnyProperties.class)
@ConditionalOnProperty(name = "qny.enable", havingValue = "true")
public String upToken(){
Auth auth = Auth.create(qnyProperties.getAccessKey(), qnyProperties.getSecretKey());
return auth.uploadToken(qnyProperties.getBucket());
}
}
这里的核心注解是Spring boot中有个注解@ConditionalOnProperty,这个注解能够控制某个configuration是否生效。具体操作是通过其两个属性name以及havingValue来实现的,其中name用来从application.properties中读取某个属性值,如果该值为空,则返回false;如果值不为空,则将该值与havingValue指定的值进行比较,如果一样则返回true;否则返回false。如果返回值为false,则该configuration不生效;为true则生效。