这篇文章主要介绍了springboot如何静态加载@configurationProperties,本文一个错误案例和成功案例结合实例代码给大家介绍的非常详细,需要的朋友可以参考下
平时开发,基本不改变的常量我们都放在了配置项里,如properties或yml文件里,这个时候为了只在启动时候进行加载。如何做呢?
我们通过springboot的 @ConfigurationProperties 注解和static静态化对应属性进行。
但如果操作不当,会导致加载的数据为空,至于为什么,看下面的案例。
1、错误案例
//错误1:get\set都是静态方法
@Component
@ConfigurationProperties(prefix = "mobile")
public class MobileConfig
{
public static Integer preview;
public static Integer getPreview() {
return preview;
}
public static void setPreview(Integer preview) {
MobileConfig.preview = preview;
}
}
//错误2:跟第一种差不多,只是用了lombok注解代替了get\set方法,get\set也都是静态方法
@Data
@Component
@ConfigurationProperties(prefix = "mobile")
public class MobileConfig
{
public static Integer preview;
}
2、成功案例
@Component
@ConfigurationProperties(prefix = "mobile")
public class MobileConfig
{
public static Integer preview;
public static Integer getPreview() {
return preview;
}
public void setPreview(Integer preview) {
MobileConfig.preview = preview;
}
}
@Data
@Component
@ConfigurationProperties(prefix = "mobile")
public class MobileConfig
{
public static Integer preview;
public void setPreview(Integer preview) {
MobileConfig.preview = preview;
}
}
3、原因
spring在注入的时候,需要调用set 方法,如果这个方法是静态方法,就没法动态注入了,所以只需要把get方法加入static作为静态方法即可,如果用了@Data,只需要重写set方法即可。
到此这篇关于springboot如何静态加载@configurationProperties的文章就介绍到这了,更多相关springboot静态加载@configurationProperties内容请搜索编程学习网以前的文章希望大家以后多多支持编程学习网!
本文标题为:springboot如何静态加载@configurationProperties


基础教程推荐
- 用java实现扫雷游戏 2022-12-06
- SpringBoot配置文件中密码属性加密的实现 2023-03-11
- 全局记录Feign的请求和响应日志方式 2023-01-09
- 一文了解Java 线程池的正确使用姿势 2023-06-17
- Project Reactor源码解析publishOn使用示例 2023-04-12
- Java去掉小数点后面无效0的方案与建议 2023-02-18
- Java使用EasyExcel进行单元格合并的问题详解 2023-01-18
- Java File类的概述及常用方法使用详解 2023-05-18
- 工厂方法在Spring框架中的运用 2023-06-23
- JVM分析之类加载机制详解 2023-04-06