配置文件
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