一、什么是classpath
classpath 指的就是 *.java 文件、資源文件等編譯后存放的位置,對於 Maven 項目就是指 target/classes 這個路徑,只要編譯后的文件在這個目錄下,springboot 就可以找到,我們這里指的是 Maven 項目, Java Web 項目可能會有區別.
二、自定義springboot配置文件路徑
springboot 項目配置文件 application.properties/application.yml 默認放置的位置是 classpath:/、classpath:/config/、file:./、file:./config/ 這4個位置.只要我們編譯后的文件位於這 4 個位置,springboot 就可以加載配置文件.但有時候我們需要以環境名稱為標識,配置多個環境的配置文件.如下我們需要將配置文件放置在指定的環境標識下.
如上圖我們的資源文件的路徑已經不再是 springboot 默認的配置路徑了,因此 springboot 啟動時將無法加載配置文件,需要我們在啟動類中手動指定配置文件的加載路徑了.
@SpringBootApplication
public class Springboot01Application {
public static void main(String[] args) {
// springboot 默認的配置文件路徑
// String addClassPath = "spring.config.location:classpath:/";
// 自定義的配置文件路徑
String addClassPath = "spring.config.additional-location:classpath:/";
addClassPath += ",classpath:/config/env/";
new SpringApplicationBuilder(Springboot01Application.class).
properties("spring.config.name:application", addClassPath).build().run(args);
}
}
三、多 profiles 配置文件的切換
我們平時開發項目的時候,在不同的時期會存在不同的環境配置文件,例如: application-dev.properties、application-sit.properties、application-uat.properties、application-pro.properties,那么我們運行項目的時候如何做到根據當前所處的環境來切換對應的環境配置文件呢?
springboot 為我們提供了切換配置文件的方式,我們在編寫配置文件時,文件名可以是: application-{profile}.properties 或者是 application-{profile}.yml
1、application-{profile}.properties方式
一、各環境配置文件如下:
application-dev.properties
person.name=xiaomaomao-dev
person.pet=dog-dev
person.hobby=LOL-dev
person.cleverLevel=nine-dev
application-sit.properties
person.name=xiaomaomao-sit
person.pet=dog-sit
person.hobby=LOL-sit
person.cleverLevel=nine-sit
application-uat.properties
person.name=xiaomaomao-uat
person.pet=dog-uat
person.hobby=LOL-uat
person.cleverLevel=nine-uat
application-pro.properties
person.name=xiaomaomao-pro
person.pet=dog-pro
person.hobby=LOL-pro
person.cleverLevel=nine-pro
通過 application.properties 來選擇需要激活的配置文件
spring.profiles.active=sit
二、實體類
@Configuration
@PropertySource("classpath:config/env/application.properties")
@ConfigurationProperties(prefix = "person")
// 省略了 get/set
public class Person {
private String name;
private String pet;
private String hobby;
private String cleverLevel;
}
三、控制器
@RestController
public class SpringbootProfileController {
@Autowired
private ApplicationContext ioc;
@RequestMapping(value = "/profile")
public String testProfiles() {
Person person = ioc.getBean("person", Person.class);
System.out.println(person);
return "hello profiles!!!";
}
}
四、測試結果
2、application.yaml方式
spring:
profiles:
active: uat # 指定激活哪個配置文件
---
server:
port: 8082
spring:
profiles: dev
---
server:
port: 8083
spring:
profiles: sit
---
server:
port: 8084
spring:
profiles: uat
參考:https://blog.csdn.net/m0_37735176/article/details/89085843