SpringBoot的配置文件切换
Why?
在家和学校的服务器不一样,有时候需要来回切换配置
- 数据库ip、端口
- 程序运行端口
- redis ip 和端口
很麻烦
如下 我们不同的环境下的配置文件中 person.name不同 ,需要更改
内部配置文件
两个原始配置文件: 任何时候都会加载
- application.properties
- application.yaml
指定环境配置文件
我们可以按照需要指定很多个环境
如:生产环境product、测试环境test、公司环境、家庭环境
命名规则:application-{env}.yaml
env随便写
如何更改?
两种方法:
- 在原始配置文件中 写入配置
- 用命令行(cmd)指定配置文件环境
方法1:在原始配置文件中 写入配置
spring:
profiles:
active: home
测试:成功
当然 也可以改为
spring:
profiles:
active: home
将 home 改为 crop、prod、test 都可以
方法2:用命令行(cmd)指定配置文件环境
java -jar xxx.jar --spring.profiles.active=home --person.name=haha
👆 同时可以在后面 修改配置 --person.name=haha
打完jar包后 用命令行运行:没有一点问题
通过注解指定环境配置属性
@Profile条件装配功能
@Data
@Component
@ConfigurationProperties("person")//在配置文件中配置
public class Person{
private String name;
private Integer age;
}
分文件配置
public interface Person {
String getName();
Integer getAge();
}
@Profile("test")//加载application-test.yaml里的
@Component
@ConfigurationProperties("person")
@Data
public class Worker implements Person {
//此时的Worker是使用 test中的 person配置
private String name;
private Integer age;
}
@Profile(value = {"prod","default"})//加载application-prod.yaml里的
@Component
@ConfigurationProperties("person")
@Data
public class Boss implements Person {
//此时的Boss类 是使用 prod中的person的配置
private String name;
private Integer age;
}
@Autowired
private Person person;
@GetMapping("/")
public String hello(){
//激活了prod,则返回Boss;激活了test,则返回Worker
return person.getClass().toString();
}
多个配置文件 也可以激活一组
spring.profiles.active=production
spring.profiles.group.production[0]=proddatabase
spring.profiles.group.production[1]=prodredis
外部配置文件
-
外部配置源
Java属性文件。
YAML文件。
环境变量。
命令行参数。 -
配置文件查找位置
-
classpath 根路径。
-
classpath 根路径下config目录。
-
- jar包当前目录。
- jar包当前目录的config目录。
- /config子目录的直接子目录。
-
配置文件加载顺序:
-
当前jar包内部的application.properties和application.yml。
-
当前jar包内部的application-{profile}.properties 和 application-{profile}.yml。
-
引用的外部jar包的application.properties和application.yml。
-
引用的外部jar包的application-{profile}.properties和application-{profile}.yml。
指定环境优先,外部优先,后面的可以覆盖前面的同名配置项。
-
classpath 根路径下config目录
jar包当前目录
jar包当前目录的config目录。