首先贴上Nacos配置:
appblog:
response:
mapping:
key1: Joe.Ye
key2: www.appblog.cn
risk:
enable: false
可以看到配置里面一个maps集合,以下演示如何动态的去读取key1和key2的数据
类映射
@Data
@Component
@ConfigurationProperties(prefix = "appblog.response")
public class NacosConfig {
//注意这里的maps要与yml里的配置名对应
private Map<String, String> mapping;
public String get(String key) {
return mapping.get(key);
}
}
示例使用代码:
@RestController
public class NacosController {
@Autowired
private NacosConfig config;
@GetMapping("/getNacosValue")
public String getNacosValue(String key) {
return config.get(key);
}
}
优点:配置简单
缺点:不支持多配置映射
方法映射
@Data
@Configuration
@RefreshScope
public class NacosConfig {
@Value("${appblog.risk.enable}")
private boolean enable;
@Bean
@ConfigurationProperties(prefix = "appblog.response.mapping")
public Map<String, String> mapping() {
// old key still exist when delete this key on nacos
return new HashMap<>();
}
}
示例使用代码:
@RestController
public class NacosController {
@Autowired
private NacosConfig config;
@GetMapping("/getNacosValue")
public String getNacosValue(String key) {
return config.mapping().get(key);
}
}
优点:支持多配置映射
缺点:配置稍微复杂




