一、问题描述
Spring Cloud Config Client 控制类添加 @RefreshScope 获取不到配置值,控制类代码如下:
package com.chaoyue.configclient.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RefreshScope
@RestController
public class ConfigClientController {
@Value("${config.info}")
private String configInfo;
@GetMapping("/configInfo")
private String getConfigInfo() {
return configInfo;
}
}
二、解决方法
注意:不能在控制类直接添加注解 @RefreshScope,否则获取的配置值为空
1.新建数据配置类
新建数据配置类,添加注解 @RefreshScope
package com.chaoyue.configclient.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
@Component
@RefreshScope
public class ConfigData {
@Value("${config.info}")
private String configInfo;
public String getConfigInfo() {
return configInfo;
}
}
2.修改控制类
修改控制类:
package com.chaoyue.configclient.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ConfigClientController {
@Autowired
private ConfigData configData;
@GetMapping("/configInfo")
private String getConfigInfo() {
return configData.getConfigInfo();
}
}