SpringBoot配置文件(Profile)环境切换

SpringBoot的配置文件切换

Why?

在家和学校的服务器不一样,有时候需要来回切换配置

  • 数据库ip、端口
  • 程序运行端口
  • redis ip 和端口

很麻烦

如下 我们不同的环境下的配置文件中 person.name不同 ,需要更改

image-20220325165929468

内部配置文件

两个原始配置文件: 任何时候都会加载

  1. application.properties
  2. application.yaml

指定环境配置文件

我们可以按照需要指定很多个环境

如:生产环境product、测试环境test、公司环境、家庭环境

命名规则:application-{env}.yaml env随便写

image-20220325165140025

如何更改?

两种方法:

  1. 在原始配置文件中 写入配置
  2. 用命令行(cmd)指定配置文件环境

方法1:在原始配置文件中 写入配置

spring:
  profiles:
    active: home

image-20220325165523214

测试:成功

image-20220325170049719

当然 也可以改为

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包后 用命令行运行:没有一点问题

image-20220325170424773

通过注解指定环境配置属性

@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文件。
    环境变量。
    命令行参数。

  • 配置文件查找位置

    1. classpath 根路径。

    2. classpath 根路径下config目录。

  1. jar包当前目录。
  2. jar包当前目录的config目录。
  3. /config子目录的直接子目录。
  • 配置文件加载顺序:

    1. 当前jar包内部的application.properties和application.yml。

    2. 当前jar包内部的application-{profile}.properties 和 application-{profile}.yml。

    3. 引用的外部jar包的application.properties和application.yml。

    4. 引用的外部jar包的application-{profile}.properties和application-{profile}.yml。

      指定环境优先,外部优先,后面的可以覆盖前面的同名配置项。

classpath 根路径下config目录

image-20220325171951080

jar包当前目录

image-20220325172327638

jar包当前目录的config目录。

image-20220325173205511

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值