maven profile切换正式环境和测试环境

时间:2023-03-09 16:12:08
maven profile切换正式环境和测试环境

有时候,我们在开发和部署的时候,有很多配置文件数据是不一样的,比如连接mysql,连接redis,一些properties文件等等

每次部署或者开发都要改配置文件太麻烦了,这个时候,就需要用到maven的profile配置了

1,在项目下pom.xml的project节点下创建了开发环境和线上环境的profile

    <profiles>
<profile>
<id>dev</id>
<properties>
<env>dev</env>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>prd</id>
<properties>
<env>prd</env>
</properties>
</profile>
</profiles>

其中id代表这个环境的唯一标识,下面会用到
properties下我们我们自己自定义了标签env,内容分别是dev和prd。

activeByDefault=true代表如果不指定某个固定id的profile,那么就使用这个环境

2,下面是我们resources下的目录,有两个目录,dev和prd,在开发时,我们使用dev下的配置文件,部署时候使用prd下的配置文件

maven profile切换正式环境和测试环境

3配置pom.xml,如果直接install,那么就会找到默认的id为dev的这个profile,然后会在里面找env的节点的值,

接着就会执行替换,相当于将src/main/resources/dev这个文件夹下的所有的配置文件打包到classes根目录下。

    <build>
<finalName>springmvc2</finalName>
<resources>
<resource>
<directory>src/main/resources/${env}</directory>
</resource>
</resources>
</build>

在idea下指定打包时指定profile的id

1第一步

maven profile切换正式环境和测试环境

2第二步

maven profile切换正式环境和测试环境

3第三步

maven profile切换正式环境和测试环境

4第四步,执行打包命令

maven profile切换正式环境和测试环境

这个时候target下springmvc项目下的classes根目录下有了env.properties,并且里面内容是我们指定的那个env.properties,

但是发现resources下的aa.properties文件没有被打包进去,那是因为我们只指定了resources/prd下的文件打包到根目录下,并没有指定其他文件

我们在pom.xml下的resources节点下新增规则

<resource>
<directory>src/main/resources</directory>
<excludes>
<exclude>dev/*</exclude>
<exclude>prd/*</exclude>
</excludes>
</resource>

再执行打包就会将resources下的除了dev文件夹和prd文件夹的其他所有文件打包到classes根目录下了

最后注意:如果有其他配置文件在src/main/java目录下,也是可以这样指定的,但是要指定

<includes>
<include>*.xml</include>
</includes>

不然会将java类当配置文件一块放到classes根目录下,加了include就会只匹配符合条件的放到target的classes根目录下

最后放我的所有的配置

   <profiles>
<profile>
<id>dev</id>
<properties>
<env>dev</env>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>prd</id>
<properties>
<env>prd</env>
</properties>
</profile>
</profiles> <build>
<finalName>springmvc</finalName>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<excludes>
<exclude>dev/*</exclude>
<exclude>prd/*</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/resources/${env}</directory>
</resource>
</resources>
</build>