使用Maven Profile构建不同环境配置

一个项目可以部署在不同的环境当中,maven 的 profile 针对不同的环境指定各自的环境。在 pom.xml 的 profile 中,可以根据不同的环境定制环境配置,最多的配置莫过于数据库的配置,下面以数据库配置为实例,演示配置过程:

新建一个Maven的Web 工程实验

然后建立如下文件结构

然后在pom文件添加如下内容:

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>cn.cuit.maven</groupId>
	<artifactId>profile-maven</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>profile-maven Maven Webapp</name>
	<url>http://maven.apache.org</url>

	<profiles>
		<profile>
			<!-- dev开发环境 -->
			<id>dev</id>
			<activation>
				<activeByDefault>true</activeByDefault>
			</activation>
			<build>
				<filters>
					<filter>src/main/resources/filters/dev/config.properties</filter>
				</filters>
			</build>
		</profile>

		<profile>
			<!-- uat测试环境 -->
			<id>uat</id>
			<build>
				<filters>
					<filter>src/main/resources/filters/uat/config.properties</filter>
				</filters>
			</build>
		</profile>

		<profile>
			<!-- prd生成环境 -->
			<id>prd</id>
			<build>
				<filters>
					<filter>src/main/resources/filters/prd/config.properties</filter>
				</filters>
			</build>
		</profile>
	</profiles>

	<dependencies>
		
	</dependencies>

	<build>
		<finalName>profile-maven</finalName>

		<resources>
			<resource>
				<directory>src/main/resources</directory>
				<includes>
					<include>**/*.properties</include>
				</includes>
				<filtering>true</filtering>
			</resource>
			<resource>
				<directory>src/main/resources</directory>
				<includes>
					<include>**/*.xml</include>
					<include>**/*.txt</include>
				</includes>
                <!-- 是否过滤 -->
				<filtering>false</filtering>
			</resource>
		</resources>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-resources-plugin</artifactId>
                <version>3.1.0</version>
				<configuration>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

四个properties文件的内容如下【三个不同环境的文件和一个真正填充环境配置的文件,即在在通过Spring扫描的时候配置应该是用properties/config.properties文件】:

dev:

jdbc.driverClassName=com.mysql.jdbc.Driver 
jdbc.url=jdbc:mysql:///dev 
jdbc.username=dev 
jdbc.password=xyz

uat:

jdbc.driverClassName=com.mysql.jdbc.Driver 
jdbc.url=jdbc:mysql:///uat
jdbc.username=uat
jdbc.password=xyz

prd:

jdbc.driverClassName=com.mysql.jdbc.Driver 
jdbc.url=jdbc:mysql:///prd
jdbc.username=prd
jdbc.password=xyz

真正填充上面的配置文件:properties/config.properties

jdbc.driverClassName=com.mysql.jdbc.Driver 
jdbc.url=${jdbc.url}
jdbc.username=${jdbc.username}
jdbc.password=${jdbc.password}

开始测试:

 再试一个uat:

 

>>>>>>>>>>>>>>>>>>>>>>请各路大神多多关照<<<<<<<<<<<<<<<<<<<<<<<<<< 

猜你喜欢

转载自blog.csdn.net/weixin_42465125/article/details/87912393