在软件开发和部署过程中,我们的软件往往需要在不同的运行环境中运行,例如:开发人员本地开发环境、测试团队的测试环境、生产仿真环境、正式生产环境,不同的公司可能还会有更多的环境需要对项目配置进行动态切换。
- maven的profile + resources + filter实现
【1】配置项目中需要用到的环境
<profiles>
<!--配置本地环境 -->
<profile>
<id>DEV</id>
<properties>
<env>dev</env>
</properties>
</profile>
<!--配置测试环境 -->
<profile>
<id>UAT</id>
<properties>
<env>test</env>
</properties>
</profile>
<!--配置生产环境 -->
<profile>
<id>PROD</id>
<properties>
<env>prod</env>
</properties>
</profile>
</profiles>
【2】实现环境文件配置,这种实现方式,真正的文件夹会引用传参过来profile环境的值,多余的各环境文件夹都会排除。
<build>
<finalName>demo</finalName>
<!-- 资源根目录排除各环境的配置,防止在生成目录中多余其它目录 -->
<resources>
<resource>
<directory>src/main/resources</directory>
<excludes>
<exclude>envconfig/dev/*</exclude>
<exclude>envconfig/prod/*</exclude>
<exclude>envconfig/test/*</exclude>
</excludes>
<filtering>true</filtering>
</resource>
</resources>
<filters>
<filter>${basedir}/src/main/resources/envconfig/${env}/jdbc.properties</filter>
</filters>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<!-- 设置JDK版本 -->
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
起作用的配置文件配置
#配置mysql驱动
jdbc.driver=${jdbc.driver}
#配置数据库地址
jdbc.url=${jdbc.url}
#配置数据库账号
jdbc.username=${jdbc.username}
#配置数据库密码
jdbc.password=${jdbc.password}
#配置数据库最大连接数
c3p0.maxPoolSize=${c3p0.maxPoolSize}
#配置数据库最小连接数
c3p0.minPoolSize=${c3p0.minPoolSize}
#配置关闭后不能commit
c3p0.autoCommitOnClose=${c3p0.autoCommitOnClose}
#配置连接超时时间
c3p0.checkoutTimeout=${c3p0.checkoutTimeout}
#配置连接失败
c3p0.acquireRetryAttempts=${c3p0.acquireRetryAttempts}
也可以保留需要环境的文件夹,不需要再配置引用环境的文件了,只需配置各个环境的文件夹
<build>
<finalName>demo</finalName>
<!-- 资源根目录排除各环境的配置,防止在生成目录中多余其它目录 -->
<resources>
<resource>
<directory>src/main/resources</directory>
<excludes>
<exclude>envconfig/dev/*</exclude>
<exclude>envconfig/prod/*</exclude>
<exclude>envconfig/test/*</exclude>
</excludes>
<filtering>true</filtering>
</resource>
<!--根据传的profiles的值,放开资源根目录需要的环境的配置,生成目录中去除了多余其它目录-->
<resource>
<directory>src/main/resources</directory>
<includes>
<include>envconfig/${env}/jdbc.properties</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<!-- 设置JDK版本 -->
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>