@ConfigurationProperties 和 @EnableConfigurationProperties 的作用

有时候,我们希望从配置文件中获取一系列配置信息,除了使用@Value注解外,还有一种更好的方式,就是使用@ConfigurationProperties注解。

比如,假设在配置文件中存在如下 OSS 配置信息:

spring:
oss:
enable: true
bucket-name: local

我们可以在对应的实体类上,使用@ConfigurationProperties注解,并指定前缀为spring.oss,如下:

@Data
@ConfigurationProperties(prefix = "spring.oss")
public class FileProperties {
private Boolean enable;
/**
* 默认的存储桶名称
*/
private String bucketName = "local";
}

这样,我们就可以很方便的获取到配置文件中的配置信息,而无需使用@Value注解。

但是,仅用@ConfigurationProperties注解,并不能将配置文件中的配置信息注入到对应的实体类中,也无法从容器中获取到对应的实体类,还需要使用@EnableConfigurationProperties注解,如下:

@Configuration
@EnableConfigurationProperties(FileProperties.class)
public class OssAutoConfiguration {
}

也可以在加了@ConfigurationProperties注解的类上加上@Component注解,能达到@EnableConfigurationProperties注解相同的效果:

@Data
@Component
@ConfigurationProperties(prefix = "spring.oss")
public class FileProperties {
private Boolean enable;
private String bucketName = "local";
}

之后,需要用到相关配置信息时,可直接从容器中获取:

@Component
public class OssService {
@Autowired
private FileProperties fileProperties;
}

所以@EnableConfigurationProperties注解的作用是:使使用@ConfigurationProperties注解的类生效。

另外,如果存在嵌套的配置信息,比如:

spring:
oss:
enable: true
bucket-name: local
aliyun:
endpoint: oss-cn-beijing.aliyuncs.com
access-key: xxx
secret-key: xxx
bucket-name: local
region: cn-beijing

则在实体类中,使用@NestedConfigurationProperty注解,如下:

@Data
@ConfigurationProperties(prefix = "spring.oss")
public class FileProperties {
private Boolean enable;
private String bucketName = "local";
@NestedConfigurationProperty
private AliyunFileProperties aliyun;
}
@Data
public class AliyunFileProperties {
private String endpoint;
private String accessKey;
private String secretKey;
private String bucketName;
private String region;
}

参考:关与 @EnableConfigurationProperties 注解简单分析 @NestedConfigurationProperty 的作用

posted @   Higurashi-kagome  阅读(160)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
点击右上角即可分享
微信分享提示