SpringCloud项目中程序如何获取Nacos服务器上的配置参数
Nacos上的配置
现在的问题是在程序中如何获取途中的 config.name和config.color的值?
获取方式
方式一 :将参数封装成类
编写封装类
package com.xl.cloud.mycloudnacosconfig.utils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import lombok.Data;
/**
* 将Nacos中的配置的参数,封装起来
* @author Administrator
*
*/
@ConfigurationProperties(prefix="config")
@Component
@Data
@RefreshScope
public class UserConfig {
private String name;
private String location;
}
应用封装类
package com.xl.cloud.mycloudnacosconfig.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.xl.cloud.mycloudnacosconfig.service.BasicInfoService;
import com.xl.cloud.mycloudnacosconfig.utils.UserConfig;
@Service
public class BasicInfoServiceImpl implements BasicInfoService {
@Autowired
private UserConfig userConfig;
@Override
public String save(String info) {
return "this is the return :"+userConfig.getName();
}
}
验证
启动Nacos,及测试项目。并访问接口:localhost:8083/config
package com.xl.cloud.mycloudnacosconfig.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.xl.cloud.mycloudnacosconfig.service.BasicInfoService;
/**
*
* @author Administrator
*
*/
@RestController
@RefreshScope
public class MyNacosConfigController {
/**
* 获取Nacos中配置的color的值, 这里冒号后面的green表示默认值
*/
@Value("${config.color:green}")
private String theColor;
@Autowired
private BasicInfoService basicInfoService;
@RequestMapping("/config")
public String getConfig() {
String str = basicInfoService.save("aaa");
return str+" ,color IS "+theColor;
}
}
以上说明获取配置参数成功。
方式二:直接使用@Value(“${config.color:green}”)形式
形如:
验证
如上图所示,获取成功。