开发、生产、测试中的配置属性是一样的,那就需要配置共享,修改一次,多环境都可使用,而不需要多环境都修改。
微服务启动时会从Nacos读取多个配置文件:
- [spring.application.name]-[spring.profile.active].yaml,如userservice-dev.yaml
- [spring.application.name].yaml,如userservice.yaml
无论profile如何变化,[spring.application.name].yaml这个文件一定会加载,因此多环境共享配置可以写入这个文件。
添加userservice.yaml配置
配置内容为
pattern: envSharedValue: wow
修改配置类
添加private String envSharedValue;
package com.yy.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
//添加get与set方法
@Component
//将此类注入成一个Bean
@ConfigurationProperties(prefix = "pattern")
//前缀与变更加起来,匹配对应配置文件
public class PatternProperties {
private String dateformat;
private String envSharedValue;
}
修改Controller
package com.yy.controller;
import com.yy.config.PatternProperties;
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.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@RestController
@RequestMapping("/user")
//@RefreshScope
public class UserController {
// @Value("${pattern.dateformat}")
// private String dateformat;
@Autowired
private PatternProperties patternProperties;
@GetMapping("now")
public String now(){
// return LocalDateTime.now().format(DateTimeFormatter.ofPattern(dateformat));
return LocalDateTime.now().format(DateTimeFormatter.ofPattern(patternProperties.getDateformat()));
}
@GetMapping("prop")
public PatternProperties patternProperties(){
// return LocalDateTime.now().format(DateTimeFormatter.ofPattern(dateformat));
return patternProperties;
}
}
对应bootstrap.yml文件
spring:
application:
name: userservice
profiles:
active: dev # 环境
cloud:
nacos:
server-addr: localhost:8848 # nacos地址
config:
file-extension: yaml # 文件后缀名
复制userservice
添加port与profiles
启动访问
可看见test无法访问到userservice-dev.yaml中的配置内容。
日志区别
同时日志也可以看出区别,dev加载了两个配置,test只加载了一个配置
多种配置优先级
同一个配置属性,存在三个文件中,优先级如下:
服务名-profile.yaml > 服务名称.yaml > 本地配置



