@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 的作用
分类:
计算机
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY