springboot项目启动时候可以指定加载配置文件,但是对于war包来讲,加载指定配置文件就有些麻烦了,这里采取另外一种形式,maven打包的时候加参数,指定加载的配置文件是哪个。
一、修改pom.xml文件
在pom.xml种加入下边的profiles
<profiles>
<profile>
<!-- 开发环境 -->
<id>dev</id>
<properties>
<profiles.active>dev</profiles.active>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<!-- 测试环境 -->
<id>test</id>
<properties>
<profiles.active>test</profiles.active>
</properties>
</profile>
<profile>
<!-- 生产环境 -->
<id>pro</id>
<properties>
<profiles.active>pro</profiles.active>
</properties>
</profile>
</profiles>
<build>
<resource>
<!-- 配置文件从哪里读取,`environment`为上方值如:`dev` -->
<directory>src/main/resources/config/${environment}</directory>
<filtering>true</filtering>
<!-- 配置文件生成在哪里,目标路径 -->
<!-- <targetPath>config</targetPath> 注释掉默认放置在classess目录下-->
</resource>
</build>
二、文件结构
三、打包命令
mvn clean package -P dev
编译和运行都会按照指定的配置文件进行打包。
注意:在用idea时候,最好把 【将IDE构建/运行委托给Maven】勾选上。把IDE的Build/Run操作委托给Maven来进行,让两者统一,意味着IDE和Maven始终使用相同的classpath进行编译等。在File -> Settings -> Build,Execution,Deployment -> Build Tools -> Maven -> Runner对话框下,勾选“Delegate IDE build/run actions to Maven”。这样,当点击绿色箭头运行的时候,顺带执行的Build就是Maven的Build,那么只要maven能成功,操作就没问题。