nacos配置中心的自定义配置自动刷新

本文解析了Spring Boot中@ConfigurationProperties与@Configuration的UserProperties类,展示了如何配置并自动刷新username和userProperties。重点讨论了@RefreshScope对username和userProperties的影响,并通过实例说明了配置文件修改后接口返回的变化。
摘要由CSDN通过智能技术生成

配置文件

username: ym
user:
  name: ssss
  age: 154

JAVA代码

@Data
@ConfigurationProperties(prefix = "user")
@Configuration
public class UserProperties {
    private String name;
    private int age;
}
package com.woyaoce.paperapi.core.common.controller;

import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.woyaoce.paperapi.properties.RedisPoolProperties;
import com.woyaoce.paperapi.properties.UserProperties;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author yangmin
 * @version 1.0
 * @description: TODO
 * @date 2022/2/22 16:46
 */
@RestController
@RequestMapping("/test")
@RefreshScope
public class TestController {

    @Value(value = "${username}")
    private String username;

    @Autowired
    private UserProperties userProperties;

    @GetMapping("/")
    public String getName() {
        return userProperties.toString()+"!!!!!!!!!!"+username;
    }
}

以上代码解释:
userProperties 不添加@RefreshScope注解也会自动刷新;
username 必须添加@RefreshScope注解才会自动刷新

测试:

在这里插入图片描述
修改配置文件信息

username: yangmin
user:
  name: yangmin
  age: 30

重新请求接口的结果:
在这里插入图片描述
参考:https://nacos.io/zh-cn/docs/quick-start-spring-cloud.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值