在 Spring Boot 中,可以使用 Profiles 來(lái)區(qū)分不同環(huán)境下的配置
在 src/main/resources
目錄下,為每個(gè)環(huán)境創(chuàng)建一個(gè)配置文件,例如:
例如,在 application-dev.yml
中添加:
app:
environment: development
application.yml
)中設(shè)置默認(rèn)的 Profile:spring:
profiles:
active: dev
@Profile
注解指定組件或配置類適用于哪些 Profile:例如,創(chuàng)建一個(gè)只在開發(fā)環(huán)境下使用的 Bean:
@Configuration
@Profile("dev")
public class DevConfiguration {
@Bean
public MyService myService() {
return new MyDevService();
}
}
在需要?jiǎng)討B(tài)切換 Profile 的地方,可以使用 ConfigurableEnvironment
和 ConfigurableApplicationContext
接口:
@Autowired
private ConfigurableApplicationContext context;
public void switchToDevProfile() {
ConfigurableEnvironment environment = context.getEnvironment();
environment.setActiveProfiles("dev");
// 重新加載上下文
context.refresh();
}
在啟動(dòng) Spring Boot 應(yīng)用時(shí),可以通過(guò)命令行參數(shù) --spring.profiles.active=profileName
來(lái)激活指定的 Profile。例如:
java -jar myapp.jar --spring.profiles.active=test
在啟動(dòng) Spring Boot 應(yīng)用之前,可以設(shè)置環(huán)境變量 SPRING_PROFILES_ACTIVE
來(lái)激活指定的 Profile。例如,在 Linux 系統(tǒng)中:
export SPRING_PROFILES_ACTIVE=prod
java -jar myapp.jar
通過(guò)這些方法,你可以在 Spring Boot 中實(shí)現(xiàn)復(fù)雜的 Profiles 邏輯,以便根據(jù)不同的環(huán)境加載不同的配置。