Maven学习笔记(六)—— profiles多环境配置

在开发过程中,我们的项目会存在不同的运行环境,比如开发环境、测试环境、生产环境,而我们的项目在不同的环境中,有的配置可能会不一样,比如数据源配置、日志文件配置、以及一些软件运行过程中的基本配置,那每次我们将软件部署到不同的环境时,都需要修改相应的配置文件,这样来回修改,很容易出错,而且浪费劳动力。
可以用Maven的profile,在打包时加个参数就可以实现想用哪个环境的配置文件就打包那个环境的配置文件,提高了效率。


项目结构
在这里插入图片描述
resources里面的dev、pro、test文件夹中各有一个log4j.properties文件

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>  

<properties>里面的<profiles.active>是自己自定义的名称,后面可以用它在pom或者properties文件中取值。
配置maven资源文件打包规则,打包资源文件时,需要通过profile里面的profiles.active的值来切换不同环境的资源文件。
<activeByDefault>true</activeByDefault>表示当前的profile默认激活

profiles结合resources,可以实现maven打包时指定打包进去的文件

 <resources>
     <resource>
     	 <targetPath>${project.build.directory}/classes</targetPath>
         <directory>src/main/resources</directory>
         <!-- 这个filter必须要设为true,用于替换 ${…} 的值 -->
          <filtering>true</filtering>
          <includes>
                <include>spring/*</include>
           </includes>
      </resource>
      <resource>
      		<targetPath>${project.build.directory}/classes</targetPath>
            <!-- 这里会直接把${profiles.active}对应文件夹下的内容打包到classpath下 -->
            <directory>src/main/resources/${profiles.active}</directory>
      </resource>
  </resources>

注意:这里由于用了<directory>src/main/resources/${profiles.active}</directory>,它是把${profiles.active}对应文件夹下的内容打包到classpath下面了,所以读取${profile.active}文件夹下的propertis文件的路径为 classpath:xxx.properties

标签讲解

<targetPath>:是指将文件输出到的位置(默认target/classes目录)
<directory>:是指将指定的目录打包
<includes>:将<directory>这个目录中指定包含哪些文件进行打包
<exclude>:将<directory>这个目录中指定排除哪些文件(打包不加入)
<filtering>:它会使用系统属性或者项目属性的值替换资源文件(*.properties,*.xml)当中 ${…} 符号的值
${project.build.directory}:指构建目录,即target目录
${basedir}:项目的根目录

来看生成的target目录结构
在这里插入图片描述
可以看到spring文件夹(包括里面的所有文件)都添加进了构建目录,然后classpath路径下多了一个
log4j.properties文件,这就是默认激活状态下的dev(开发分支)文件夹中的log4j.properties文件

最后,可以通过mvn package –P 这里填你的profile的id值命令来指定将哪个环境进行打包
特别注意:P是大写的

猜你喜欢

转载自blog.csdn.net/shijiujiu33/article/details/89460721