关键字:@ConfigurationProperties
实体封装类:lbvroot.vcore.app.AppProps.java
一、注解作用
application.properties或者application.yml是spring boot项目的主要配置文件,
- 包括各种官方配置属性
- 也可以包函自定义的属性
@ConfigurationProperties注解能方便的把配置属性,映射到实体封装类中,以便进行被其他类引用使用。
二、详细使用说明
结合AppProps.java,来清晰明了说明使用方法
1. application.properties的配置信息
//部分配置信息#1.log and upload pathleanboot.prop.upload-path=D:/filespath/leanbootcom/#2.local:本地 | fastdfs:文件服务器 | upyun:又拍云leanboot.prop.file-platform=upyunleanboot.prop.img-platform=upyun
2. AppProps.java代码片段
@Configuration@ConfigurationProperties(prefix = "leanboot.prop")public class AppProps {//1.上传路径public static String uploadPath;//2.文件上传平台>local:本地 | fastdfs:文件服务器 | upyun:又拍云public static String filePlatform = "local";//3.图片上传平台>local:本地 | fastdfs:文件服务器 | upyun:又拍云public static String imgPlatform = "local";//setter方法不能是static的public void setUploadPath(String uploadPath) {AppProps.uploadPath = uploadPath;}public void setFilePlatform(String filePlatform) {AppProps.filePlatform = filePlatform;}public void setImgPlatform(String imgPlatform) {AppProps.imgPlatform = imgPlatform;}}
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使用就能达到目的。
//应用启动端口public static int serverPort;//对应方法,添加@Value@Value("${server.port}")public void setServerPort(int serverPort){AppProps.serverPort = serverPort;}
四、总结知识点(遵循够用原则)
- @ConfigurationProperties的基本使用方法
- @Value的基本使用
- 属性映射的静态static化
五、@ConfigurationProperties引发的idea的自动配置提示
SpringBoot Configuration Annotation Processor not configured
由于该注解,涉及到spring boot的自动配置机制,idea检验到这个注解的时候,就会发出警示,详细查看:
@ConfigurationProperties注解处理器配置元数据Metadata

