SpringBoot的profile
假设分3个环境配置:dev、test、prd
SpringBoot的配置文件名必须约定满足application-{profile}.properties的格式, 如下:
然后需要设置变量spring.profiles.active的值, 才可以激活对应的profile, 方式有:
(1) 在application.properties中设置,如下:
spring.profiles.active=dev
这种方式仅限于开发/调试阶段, 实际部署时再去修改配置文件很不方便.
(2) 实时设置Java启动参数, 会覆盖上面配置文件的值, 如下:
java -jar hello.jar --spring.profiles.active=test
或者
java -Dspring.profiles.active=test -jar hello.jar
如何减少jar包里不必要的环境配置文件?
对于上面的4个配置文件, SpringBoot打包时, 默认会把所有文件都打进jar里面, 显然很冗余.
假如打包工具是maven, 我们可以利用它的profile, 实现在资源构建时对配置文件分环境进行过滤.
maven profile的使用方式有很多, 这里介绍常用的一种, 即在pom文件里定义好profile, 然后在mvn打包时进行激活.
SpringBoot的pom文件, 如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.wx</groupId>
<artifactId>hello</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.12.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<!--定义3个profile-->
<profiles>
<profile>
<id>dev-profile</id>
<activation>
<property>
<name>maven.profile.active</name>
<value>dev</value>
</property>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<env>dev</env>
</properties>
</profile>
<profile>
<id>test-profile</id>
<activation>
<property>
<name>maven.profile.active</name>
<value>test</value>
</property>
</activation>
<properties>
<env>test</env>
</properties>
</profile>
<profile>
<id>prd-profile</id>
<activation>
<property>
<name>maven.profile.active</name>
<value>prd</value>
</property>
</activation>
<properties>
<env>prd</env>
</properties>
</profile>
</profiles>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
<!--定制打包时的资源拷贝-->
<resources>
<resource>
<directory>src/main/resources</directory>
<targetPath>./</targetPath>
<includes>
<include>application.properties</include>
<include>application-${env}.properties</include>
</includes>
</resource>
</resources>
</build>
</project>
在mvn打包时, 激活对应的profile, 如下:
mvn clean package -Dmaven.profile.active=prd
或者
mvn clean package -Pprd-profile
则最终打进jar包里的环境配置文件就只有2个, 其他环境的配置文件被过滤掉了, 如下:
如何进行配置文件敏感信息的保密?
有时候生产的配置信息比较敏感, 除了运维, 不希望其他人明眼看见, 实际中有一些解决方案, 如下:
(1) 配置项加密
这种方式, 比较烦碎, 而且一般的加密都是可逆的.
(2) jar包外部的本机配置文件
即配置文件放在jar包之外,一般会放在部署应用的那台机器上, 这个安全级别高.
(3) 统一配置中心
当然“统一配置中心”绝不是为了保密而引入的, 使用配置中心, 配置在运行时才加载到本机, 还是挺安全的, 但要保证非生产环境不能加载生产环境的配置.