背景
阅读springboot源码时,了解到spring是如何自动获取配置项的
Properties
通过 java.util.Properties 手动来读取 application.properties
@Value
@ConfigurationProperties + @EnableConfigurationProperties
使用这种方式最为优雅,向spring靠齐
第一步,定义 **Properties 类,加上 @ConfigurationProperties 注解
参照:org.springframework.boot.autoconfigure.data.redis.RedisProperties
第二步,添加一个 **Configuration 类,使用@EnableConfigurationProperties 注解引入第一步定义的class
参照:org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration
java 类建好后,在 application.properties/application.yml 配置文件添加配置项
为什么优雅?
以 RedisProperties.class 为例
1.安全:只有定义在 RedisProperties.class 的属性的配置项,才会生效
2.方便易用:一处定义,可多处使用,因为使用的将是类
3.方便管理:如果是yml格式,很有层次感,配置项和类的属性定义将会层次分明(支持属性是对象或者list)
小问题
使用过程总的来说比较繁琐,没有@Value方便