一、@Value注解读取配置
Spring框架支持使用@Value注解的方式来获取 .properties文件中的配置值,这样可以大大简化读取配置文件的代码。读取方式如下:
@Slf4j
@Service
public class OmsShipmentServiceImpl implements OmsShipmentService {
@Autowired
private OmsOrderDAO omsOrderDAO;
@Autowired
private OmsOrderContactDAO omsContactDAO;
@Value("${myConfig1.config1}")
private String config1;
@Value("${myConfig2.config2}")
private String addTrackingUri;
... ...
}
配置文件 {micro_service_name}-{branch_name}-{environment_name}.yml配置如下:
myConfig1:
config1: configValue1
myConfig2:
config2: configValue2
二、配置服务配置加载
1、配置服务默认配置
通过查看Spring Cloud Config 源码时会发现,在spring-cloud-config-server.jar包中有一个默认配置文件configserver.yml,当你的应用程序启动的时候没有读取到配置服务的配置文件,就会读取配置中心的默认配置,默认使用地址localhost:8888,默认读取Git地址为:https://github.com/spring-cloud-samples/config-repo仓库中的配置文件,文件内容如下:
info:
component: Config Server
spring
application:
name: configserver
jmx:
default_domain: cloud.config.server
cloud:
config:
server:
git:
uri: https://github.com/spring-cloud-samples/config-repo
repos:
- patterns: multi-repo-demo-*
uri: https://github.com/spring-cloud-samples/config-repo
server:
port: 8888
management:
context_path: /admin
2、配置文件命名规则:
/{application}/{profile}[/{label}]
/{application}-{profile}.yml
/{label}/{application}-{profile}.yml
/{application}-{profile}.properties
/{label}/{application}-{profile}.properties
这些文件命名格式会按照“{application}-{profile}.properties(yml)”格式匹配配置文件。label对应的是Git上的分支名称,是一个可选参数,如果没有这个参数,默认会从master分支上进行查找,如果配置了label,则会找到对应的分支下面去读取配置文件。可以根据自己的需求,选择哪种配置路径来读取。