软件编程
位置:首页>> 软件编程>> java编程>> springboot如何静态加载@configurationProperties

springboot如何静态加载@configurationProperties

作者:奇怪的守护神  发布时间:2021-12-13 16:20:13 

标签: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方法即可。

来源:https://blog.csdn.net/qq_24298751/article/details/126019483

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com