叶子的博客   Java/Ruby/PHP/JS

遇到问题时冷静对待,这或许不能解决问题
但能使你收获更多

maven构建不同环境读取不同的配置文件

众所周知maven是java开发的利器,他的强大之处不同我多说了。这次为大家带来的就是maven对应不同环境的部署,以及未来给各位介绍jenkins构建项目做铺垫。

首先,我已一个spring-boot项目为例子讲解,举一反三,其他项目也是同样原理的,或者有部分配置不同而已。

pom.xml代码:

在project根下加入

<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>product</id>
       <properties>
         <env>product</env>
       </properties>
  </profile>

 </profiles>

然后找到build根节点,在里面加入资源路径引入

<!--资源引入-->
<resources>
     <resource>
           <directory>${project.basedir}/src/main/resources/${env}</directory>
        <includes>
             <include>application.properties</include>
        </includes>
      <filtering>true</filtering><!--这个相当重要,不加就不能动态构建不同资源了-->
     </resource>
 </resources>



<!--构建的主要插件-->
 <plugins>
      <plugin>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>

 <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-war-plugin</artifactId>
      <configuration>
         <warName>tiles</warName>
       <archive>
         <addMavenDescriptor>false</addMavenDescriptor>
       </archive>
   <webResources>
       <resource>
           <directory>src/main/resources/${env}/application.properties</directory>
           <filtering>true</filtering>
       </resource>
   </webResources>
       </configuration>
 </plugin>

 </plugins>

大家请看插件中有war包的插件,这个就是最终构建成可发布版本时用到的。

当中webResources就是读取项目中的配置文件操作,请细看里面部分,directory就是读取的配置文件路径${env}大家应该都知道了,就是我们上面配置的项目环境的变量,当打包为test的时候,env = test。所以这样就能直接构建时动态读取需要的配置文件了。

最后的知识点(重要):

这样我们就能打包时传入构建项目的目标环境了。。。
命令如下:mvn clean package -P目标环境代码
如我要配置到测试环境的,那就是mvn clean package -Ptest
so:之后我会和大家探讨jenkins,那jenkins就可以约定好测试环境为test,生产是product来构建项目了。(后话)
其他配置我就不写上去了,其他只不过就是项目的名称版本和所拥有的依赖。