iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >springboot如何静态加载@configurationProperties
  • 465
分享到

springboot如何静态加载@configurationProperties

2024-04-02 19:04:59 465人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

目录1、错误案例2、成功案例3、原因平时开发,基本不改变的常量我们都放在了配置项里,如properties或yml文件里,这个时候为了只在启动时候进行加载。如何做呢? 我们通过Spr

平时开发,基本不改变的常量我们都放在了配置项里,如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内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: springboot如何静态加载@configurationProperties

本文链接: https://www.lsjlt.com/news/165462.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作