背景
一般项目上线都会有多个环境,如开发环境,预发环境,线上环境,不同环境的配置可能会不一样,下面说下如何做多环境配置。本来是很简单的一件事,但是配置过程中遇到了报错,记录下:
配置
假设有三个环境 dev pre prod,分为三个配置文件application-dev.yml, application-pre.yml, application-prod.yml 分别把这三个配置文件放到resources中,跟application.yml并列。
application.yml中添加如下配置:
spring:
profiles:
active: @profileActive@
pom中添加如下配置
<profiles>
<profile>
<id>dev</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<profileActive>dev</profileActive>
</properties>
</profile>
<profile>
<id>pre</id>
<properties>
<profileActive>pre</profileActive>
</properties>
</profile>
<profile>
<id>prod</id>
<properties>
<profileActive>prod</profileActive>
</properties>
</profile>
</profiles>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>1.5.11.RELEASE</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.6</version>
<configuration>
<delimiters>
<delimiter>@</delimiter>
</delimiters>
<useDefaultDelimiters>false</useDefaultDelimiters>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
<resource>
<directory>src/main/resources</directory>
<!-- 是否替换@xx@表示的maven properties属性值 -->
<filtering>true</filtering>
<includes>
<include>application.yml</include>
</includes>
</resource>
</resources>
</build>
profileActive对应的就是application里@profileActive@,执行时会替换掉,其中dev设置了default,默认使用dev
如果不配置 maven-resources-plugin 在idea启动时会遇到报错
Caused by: org.yaml.snakeyaml.scanner.ScannerException: while scanning for the next token
found character '@' that cannot start any token. (Do not use @ for indentation)
in 'reader', line 3, column 13:
active: @profileActive@
Caused by: org.yaml.snakeyaml.scanner.ScannerException: while scanning for the next token
found character '@' that cannot start any token. (Do not use @ for indentation)
in 'reader', line 3, column 13:
active: @profileActive@
使用mvn命令打包时可以通过命令指定
mvn clean package -Pprod
在启动java启动时可以用下面指定
–spring.profiles.active=dev