您的位置:首页 >springboot怎么静态加载@configurationProperties
发布于2023-05-12 阅读(0)
扫一扫,手机访问
平时开发,基本不改变的常量我们都放在了配置项里,如properties或yml文件里,这个时候为了只在启动时候进行加载。如何做呢?
我们通过springboot的 @ConfigurationProperties 注解和static静态化对应属性进行。
但如果操作不当,会导致加载的数据为空,至于为什么,看下面的案例。
//错误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;
}@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;
}
}spring在注入的时候,需要调用set 方法,如果这个方法是静态方法,就没法动态注入了,所以只需要把get方法加入static作为静态方法即可,如果用了@Data,只需要重写set方法即可。
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
9