網上搜集和整理如下(自己已驗證過)
1. war包在tomcat中加載外部配置文件
war包運行在獨立tomcat下時,如何加載war包外部配置application.properties,以達到每次更新war包而不用更新配置文件的目的。
SpringBoot配置文件可以放置在多種路徑下,不同路徑下的配置優先級有所不同。
可放置目錄(優先級從高到低)
- 1.file:./config/ (當前項目路徑config目錄下);
- 2.file:./ (當前項目路徑下);
- 3.classpath:/config/ (類路徑config目錄下);
- 4.classpath:/ (類路徑config下).
- 優先級由高到底,高優先級的配置會覆蓋低優先級的配置;
- SpringBoot會從這四個位置全部加載配置文件並互補配置;
想要滿足不更新配置文件的做法一般會采用1 和 2,但是這些對於運行在獨立tomcat下的war包並不比作用。
我這里采用的是SpringBoot的Profile配置。
在application.properties中增加如下配置:
spring.profiles.active=test1
- 再在tomcat根目錄下新建一個名為config的文件夾,新建一個名為application-test1.properties的配置文件。
- 完成該步驟后,Profile配置已經完成了。
- 然后還需要將剛剛新建的config文件夾添加到tomcat的classpath中。
- 打開tomcat中catalina.properties文件,在common.loader處添加**${catalina.home}/config**,此處的config即之前新建的文件夾名稱。
- 如此,大功告成。程序啟動之后,每次配置文件都會從config/application-test1.properties加載。
2.自定義配置文件
如果你不想使用application.properties作為配置文件,怎么辦?完全沒問題
java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties
或者
java -jar -Dspring.config.location=D:\config\config.properties springbootrestdemo-0.0.1-SNAPSHOT.jar
當然,還能在代碼里指定
@SpringBootApplication @PropertySource(value={"file:config.properties"}) public class SpringbootrestdemoApplication { public static void main(String[] args) { SpringApplication.run(SpringbootrestdemoApplication.class, args); } }
3.(擴展)這里詳細介紹下spring.profiles.active
默認配置 src/main/resources/application.properties
app.window.width=500 app.window.height=400
指定具體環境的配置
src/main/resources/application-dev.properties
app.window.height=300
src/main/resources/application-prod.properties
app.window.width=600 app.window.height=700
簡單的應用
package com.logicbig.example; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; @Component public class ClientBean { @Value("${app.window.width}") private int width; @Value("${app.window.height}") private int height; @PostConstruct private void postConstruct() { System.out.printf("width= %s, height= %s%n", width, height); } } package com.logicbig.example; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ExampleMain { public static void main(String[] args) { SpringApplication.run(ExampleMain.class, args); } }
運行
$ mvn spring-boot:run width= 500, height= 400 $ mvn -Dspring.profiles.active=dev spring-boot:run width= 500, height= 300 $ mvn -Dspring.profiles.active=prod spring-boot:run width= 600, height= 700