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

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