springboot怎么静态加载@configurationProperties
平时开发,基本不改变的常量我们都放在了配置项里,如properties或yml文件里,这个时候为了只在启动时候进行加载。如何做呢?我们通过springboot的@ConfigurationProperties注解和static静态化对应属性进行。但如果操作不当,会导致加载的数据为空,至于为什么,看下面的案例。1、错误案例//错误1:get\set都是静态方法@Component@ConfigurationProperties(prefix="mobile")publicclassMobileConfig{
平时开发,基本不改变的常量我们都放在了配置项里,如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方法即可。
Windows 10 是一款微软推出的经典操作系统,拥有硬件兼容性与多任务处理能力。它更偏向把系统状态查看和常用调节动作放在一起,适合需要持续观察和微调设备状态的场景。
极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。
















