问题发生:
我们知道springboot 项目中的配置文件application.properties ,几乎我们的配置信息都写在了这边,非常方便,但常常我们会多环境应用,比如开发环境 、测试环境 、正式环境 等不同的配置信息,前一段时间,由于要实现自动化部署,要改很多套环境,很麻烦,于是就利用了切换profile的办法解决了此问题
解决办法:
方法一:在pom.xml文件中指定数据源以及要切换的变量,然后在application中使用@@引用
1.首先在pom.xml文件中添加以下配置
<profiles>
<!-- 默认开发环境 -->
<profile>
<!--id唯一,不能有重复的-->
<id>dev</id>
<!--配置-->
<properties>
<!-- 环境标识,需要与配置文件的名称相对应 -->
<serviceport>8089</serviceport> <!-- serviceport为端口引用名称可自定义 -->
<zkHost>http://localhost:8983/solr</zkHost> <!-- zkHost为数据库地址名称可自定义 -->
<driverclass>oracle.jdbc.driver.OracleDriver</driverclass> <!-- driverclass为数据库驱动名称可自定义 -->
</properties>
<activation>
<!-- 默认环境,如果设置了这个,则项目运行默认 使用这个profile的配置 --> <activeByDefault>true</activeByDefault>
</activation>
</profile>
<!-- 生产环境 -->
<profile>
<id>product</id>
<properties>
<serviceport>30001</serviceport>
<zkHost>http://113.11.11.11:8983/solr</zkHost>
<driverclass>com.microsoft.sqlserver.jdbc.SQLServerDriver</driverclass>
</properties>
</profile>
</profiles>
2.接下来在application.properties 文件中加入一下配置即可
server.port=@serviceport@
spring.datasource.url=@zkHost@
spring.datasource.driver-class-name=@driverclass@
方法二:在pom.xml文件中指定开发环境 、测试环境 、正式环境 的名字,然后通过@@切换实现也行,具体步骤如下:
1.首先在pom.xml文件中添加以下配置
<profiles>
<profile>
<!-- 开发环境 -->
<id>dev</id>
<properties>
<!-- 环境标识,需要与配置文件的名称相对应 -->
<env>dev</env>
</properties>
<activation>
<!-- 设置默认激活这个配置 -->
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<!-- 测试环境 -->
<id>test</id>
<properties>
<env>test</env>
</properties>
</profile>
<profile>
<!-- 发布环境 -->
<id>prod</id>
<properties>
<env>prod</env>
</properties>
</profile>
</profiles>
2.接下来在application.properties 文件中加入一下配置即可
方法三:如果我们使用的是构建工具是Maven,也可以通过Maven的profile特性来实现多环境配置打包。pom.xml配置如下:
<profiles>
<!--开发环境-->
<profile>
<id>dev</id>
<properties>
<build.profile.id>dev</build.profile.id>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<!--测试环境-->
<profile>
<id>test</id>
<properties>
<build.profile.id>test</build.profile.id>
</properties>
</profile>
<!--生产环境-->
<profile>
<id>prod</id>
<properties>
<build.profile.id>prod</build.profile.id>
</properties>
</profile>
</profiles>
<build>
<finalName>${project.artifactId}</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources.${build.profile.id}</directory>
<filtering>false</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<classifier>exec</classifier>
</configuration>
</plugin>
</plugins>
</build>
然后通过通过执行 mvn clean package -P ${profile} 来指定使用哪个profile
注:前两个方法打包时也是通过命令 mvn clean install -P ${profile} -DskipTests打包即可(${profile} 即你定义的配置文件的名称 如dev的写法为:mvn clean install -P dev -DskipTests),还有使用.yml文件也是一样的做法,换成.yml语言写法即可
如果有不足和不正确的地方请大家多多指正,前两个方法亲测可用,第三个没试过,但是这种方法是可行的