• SpringCloud Alibaba——记录一种nacos配置中心动态刷新不起效的解决方式(@ConfigurationProperties)


    前言

    使用官方的nacos搭建对应的环境进行测试时,通常涉及到动态配置项,都会使用nacos的配置中心实现。

    Nacos服务注册和配置中心

    通常的做法,都是采取@RefreshScope注解结合@Value注解实现动态配置变更自动刷新

    但在公司自己封装的nacos组件中进行测试,会出现Could not resolve placeholder 'XXXX' in string value "${xxx.xxx.xxx}的报错信息,导致项目启动失败!

    替换方式

    每次写@RefreshScope@Value,都很麻烦。

    @Value可以使用表达式,给定默认值,这个是一个亮点!

    此处为了代码的更好阅读性,使用@ConfigurationPropertiesbean的形式来管理配置属性项。

    1、nacos中增加配置内容

    kettle:
        environment: dev
    
    • 1
    • 2

    2、编写配置接收bean

    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.stereotype.Component;
    
    @Component
    @ConfigurationProperties(prefix = KettleProperties.PREFIX)
    public class KettleProperties {
        public static final String PREFIX = "kettle";
    
        private String environment;
    
        public String getEnvironment() {
            return environment;
        }
    
        public void setEnvironment(String environment) {
            this.environment = environment;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    这里需要注意几点:

    • 注意属性大小写问题,如果是驼峰命名,则nacos中的配置列需要使用-拼接。

      如:private String envPath 时,nacos中的对应配置列为
      kettle.env-path: 99999

    • 必须写get方法!

      在使用处,需要采取getxx获取变更项

    3、使用处的使用demo

    如写一个controller,测试获取变更属性。

    @RestController
    @Api(tags = "test")
    @RequestMapping("/test")
    public class TestController {
    
        @GetMapping("/test")
        public String test(){
            return "998887654321";
        }
    
        @Autowired
        KettleProperties kettleProperties;
    
        @RequestMapping("/test3")
        public String test3(){
            return kettleProperties.getEnvironment() + "######";
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    4、测试

    分别在项目启动后,进行请求测试。
    和修改nacos中对应的配置项后,再次请求测试。

    可以发现能够随着nacos配置中心中的变更及时变更!

    注意事项

    @ConfigurationProperties使用时,针对属性,必须写get

  • 相关阅读:
    openGauss内核:SQL解析过程分析
    LCR 171.训练计划 V
    Excel 可视化教程之可视化的科学与艺术
    LLM - SFT workflow 微调工作流程
    数据库迁移工具 Flyway vs Liquibase (二)
    技术管理进阶——你遇到过耍小聪明的同学吗?
    如何快速上手短视频创作,有什么建议吗?
    为什么现在写论文都需要查重?
    单商户商城系统功能拆解28—营销中心—砍价活动
    FPGA面试题(6)
  • 原文地址:https://blog.csdn.net/qq_38322527/article/details/126352200