点击登录,精彩内容等着你

@ConfigurationProperties注解使用与static静态属性绑定

全栈侠客

2022-09-29
注解@ConfigurationProperties的通用使用方法,都是映射到封装类的private的属性中,为后面的属性的使用带来麻烦, 本周将解析该注解的使用方法与public static的属性绑定方法

关键字:@ConfigurationProperties
实体封装类:lbvroot.vcore.app.AppProps.java

一、注解作用

application.properties或者application.yml是spring boot项目的主要配置文件,

  • 包括各种官方配置属性
  • 也可以包函自定义的属性

@ConfigurationProperties注解能方便的把配置属性,映射到实体封装类中,以便进行被其他类引用使用。

二、详细使用说明

结合AppProps.java,来清晰明了说明使用方法

1. application.properties的配置信息

  1. //部分配置信息
  2. #1.log and upload path
  3. leanboot.prop.upload-path=D:/filespath/leanbootcom/
  4. #2.local:本地 | fastdfs:文件服务器 | upyun:又拍云
  5. leanboot.prop.file-platform=upyun
  6. leanboot.prop.img-platform=upyun

2. AppProps.java代码片段

  1. @Configuration
  2. @ConfigurationProperties(prefix = "leanboot.prop")
  3. public class AppProps {
  4. //1.上传路径
  5. public static String uploadPath;
  6. //2.文件上传平台>local:本地 | fastdfs:文件服务器 | upyun:又拍云
  7. public static String filePlatform = "local";
  8. //3.图片上传平台>local:本地 | fastdfs:文件服务器 | upyun:又拍云
  9. public static String imgPlatform = "local";
  10. //setter方法不能是static的
  11. public void setUploadPath(String uploadPath) {
  12. AppProps.uploadPath = uploadPath;
  13. }
  14. public void setFilePlatform(String filePlatform) {
  15. AppProps.filePlatform = filePlatform;
  16. }
  17. public void setImgPlatform(String imgPlatform) {
  18. AppProps.imgPlatform = imgPlatform;
  19. }
  20. }

3. 说明

  • @ConfigurationProperties 中prefix属性,指定配置文件的前缀:leanboot.prop,并指定默认的类属性对应的配置,是leanboot.prop前缀开始的。
  • 属性名称使用驼峰方式,跟配置文件属性进行对应,如:leanboot.prop.upload-path对应属性值:uploadPath

4. 通过set方法,达到属性的static化

  • 注意每一个属性,都是public static的,这样表示,有利于属性的使用
  • 只是提供set的方法实现,为注解@ConfigurationProperties的属性匹配提供基础方法,从而达到static化

三、混合@Value使用

如果不重写对应元素的set方法,或者一些属性,配置不是leanboot.prop前缀的,这个时候,搭配@Value使用就能达到目的。

  1. //应用启动端口
  2. public static int serverPort;
  3. //对应方法,添加@Value
  4. @Value("${server.port}")
  5. public void setServerPort(int serverPort){
  6. AppProps.serverPort = serverPort;
  7. }

四、总结知识点(遵循够用原则)

  1. @ConfigurationProperties的基本使用方法
  2. @Value的基本使用
  3. 属性映射的静态static化

五、@ConfigurationProperties引发的idea的自动配置提示

SpringBoot Configuration Annotation Processor not configured
由于该注解,涉及到spring boot的自动配置机制,idea检验到这个注解的时候,就会发出警示,详细查看:
@ConfigurationProperties注解处理器配置元数据Metadata

阅读 2665     最后编辑 2022-09-30 12:42
文章补充
评论(0) 发表新评论
  • ...暂无评论...

我是有底线的 评论与点赞5分钟更新一次
回复评论
取消关闭

请先登录