本文主要是介绍springcloud config添加@RefreshScope获取不到配置值的解决方法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
目录
- 一、问题描述
- 二、解决方法
- 1.新建数据配置类
- 2.修改控制类
一、问题描述
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 {@Autowiredprivate ConfigData configData;@GetMapping("/configInfo")private String getConfigInfo() {return configData.getConfigInfo();}
}
这篇关于springcloud config添加@RefreshScope获取不到配置值的解决方法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!