maven 项目多环境配置文件使用方式

1. 以springboot 项目为例 

使用spring profile 指定环境参数,来使用 指定环境配置文件

工程结构

在启动时指定参数 spring.profiles.active=dev 或者sit 或者uat

java -jar -Dspring.profiles.active=dev test.jar 

springboot 加载application.properties 顺序

springboot 配置文件位置加载顺序(优先级从上至下)

  • jar 包同级目录config 目录下属性配置文件
  • jar 同级目录下属性配置文件
  • jar 里src/main/resources 属性配置文件

属性配置查找顺序 (先在application-xxx.properties 中查找,在application-xxx.properties 找不到,最终会在application.properties查找)

假设各属性配置文件中有 book.name=java 属性

查找顺序为

  • 在jar 包同级目录config 目录下属性配置文件 application-xxx.propertie查找该属性
  • 在jar 同级目录下属性配置文件 application-xxx.propertie查找该属性
  • 在jar 里src/main/resources 属性配置文件 application-xxx.propertie查找该属性
  • 最终在application.properties中查找

2. maven profile 

通过maven profile 打包指定环境配置文件

mvn clean install -P sit

最终打出包只包含指定环境配置文件

工程结构如下

pom.xml 中配置

  <profiles>
		<profile>
			<id>dev</id>
			<properties>
				<profile.env>dev</profile.env>
			</properties>
			<activation>
				<activeByDefault>true</activeByDefault>
			</activation>
		</profile>
		<profile>
			<id>sit</id>
			<properties>
				<profile.env>sit</profile.env>
			</properties>
		</profile>
	</profiles>
    <build>
		<resources>
			<resource>
				<directory>${basedir}/config/${profile.env}</directory>
				<targetPath>${project.build.directory}/config/</targetPath>
			</resource>
		</resources>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
		</plugins>
   </build>

参考

https://blog.csdn.net/mayi92/article/details/77892809

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章