SpringCloud项目读取多种配置
一种是properties文件,一种是yml文件,两种文件格式都支持多种配置(profiles)。
如果没有profiles属性的话,properties与yml文件转换相对简单,
- 一个是"."一个是双空格;
简单例子:
application.yml
server:
port: 8888
application.properties
server.port=8888
如果有profiles属性,多种配置后怎么办
举个Eureka的例子
启动类代码
@SpringBootApplication
@EnableEurekaServer
public class FirstServer {
public static void main(String[] args) {
// 读取控制台输入,决定使用哪个profiles
Scanner scan = new Scanner(System.in);
String profiles = scan.nextLine();
new SpringApplicationBuilder(FirstServer.class).profiles(profiles).run(args);
}
}
用yml配置
application.yml配置文件
server:
port: 8761
spring:
application:
name: first-cloud-server
profiles: slave1
eureka:
instance:
hostname: slave1
client:
serviceUrl:
defaultZone: http://slave2:8762/eureka/
---
server:
port: 8762
spring:
application:
name: first-cloud-server
profiles: slave2
eureka:
instance:
hostname: slave2
client:
serviceUrl:
defaultZone: http://slave1:8761/eureka/
实际启动时,配置文件中用三个"-"分隔两种配置即可,只用输入slave1,slave2,便可分别按照配置启动。
用properties配置
properties文件的特性,你不能有两个同样的key,便不可能在同一文件中写两种配置,但Spring提供了如下的读取方式
- 多少个配置就要有多少个配置文件,命名有要求application-“profilesName”.properties,这个profilesName便是你的配置名。
- properties文件的内容要有
cusvar=profilesName
spring.profiles.active=profilesName
application-slave1.properties
cusvar=slave1
spring.profiles.active=slave1
server.port=8761
spring.application.name=first-cloud-server
eureka.instance.hostname=slave1
eureka.client.serviceUrl.defaultZone=http://slave2:8762/eureka/
application-slave2.properties
cusvar=slave2
spring.profiles.active=slave2
server.port=8762
spring.application.name=first-cloud-server
eureka.instance.hostname=slave2
eureka.client.serviceUrl.defaultZone=http://slave1:8761/eureka/
只用输入slave1,slave2,便可分别按照配置启动。