0
点赞
收藏
分享

微信扫一扫

springboot根据环境装配配置文件、启动加载外置配置文件

alonwang 2022-01-12 阅读 161

目录

一、profile功能

1.简介

2.application-profile功能

3.profile条件装配

4.profile分组

二、外部化配置

1.官方文档

2.获取系统的环境变量、属性(扩展)

3.外部配置源

4.配置文件(application.yaml)查找位置

5.配置文件加载顺序


一、profile功能

1.简介

为了方便多环境适配,springboot简化了profile功能。

2.application-profile功能

(1)注意事项

① 默认配置文件 application.yaml;任何时候都会加载

② 指定环境配置文件 application-{env}.yaml

③ 默认配置与环境配置同时生效,同名配置项,环境配置文件(application-{env}.yaml)优先

④ 修改配置文件的任意值,命令行优先

(2)激活方式

① 配置文件激活

application.yaml 中加入配置,即可以激活指定的配置文件application-{env}.yaml

spring:
profiles:
active: test # 指定激活的环境

② 命令行激活

# 修改激活的环境
java -jar cxf-1.0-SNAPSHOT.jar --spring.profiles.active=prod
# 修改默认的配置,命令行优先
java -jar cxf-1.0-SNAPSHOT.jar --spring.profiles.active=prod --server.port=8088

3.profile条件装配

// 可以注释方法、类,根据环境来装配
@Configuration(proxyBeanMethods = false)
@Profile("production")
public class ProductionConfiguration {

// ...
}
@Configuration
public class MyConfig {

@Profile("prod")
@Bean
public Color red(){
return new Color();
}

@Profile("test")
@Bean
public Color green(){
return new Color();
}
}
@Profile("test")
@Component
@ConfigurationProperties("person")
@Data
public class Worker implements Person {
private String name;
private Integer age;
}

@Profile(value = {"prod","default"})
@Component
@ConfigurationProperties("person")
@Data
public class Boss implements Person {
private String name;
private Integer age;
}

public interface Person {
String getName();
Integer getAge();
}

4.profile分组

spring.profiles.group.production[0]=uat
spring.profiles.group.production[1]=test

使用:--spring.profiles.active=production 激活整组的环境配置

二、外部化配置

1.官方文档

Core Features

2.获取系统的环境变量、属性(扩展)

ConfigurableApplicationContext run = SpringApplication.run(Boot09FeaturesProfileApplication.class, args);
ConfigurableEnvironment environment = run.getEnvironment();

Map<String, Object> systemEnvironment = environment.getSystemEnvironment();
Map<String, Object> systemProperties = environment.getSystemProperties();

System.out.println(systemEnvironment); // 环境变量
System.out.println(systemProperties); // 系统属性
@Value("${MAVEN_HOME}")
private String msg;

@Value("${os.name}")
private String osName;

3.外部配置源

常用:Java属性文件、YAML文件、环境变量、命令行参数等。

4.配置文件(application.yaml)查找位置

注意:后面的可以覆盖前面的同名配置项

(1) 项目classpath 根路径

(2) classpath 根路径下config目录

(3) jar包当前目录

(4) jar包当前目录的config目录

(5) /config子目录的直接子目录

5.配置文件加载顺序

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

(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

举报

相关推荐

0 条评论