原創作品,可以轉載,但是請標注出處地址:https://www.cnblogs.com/V1haoge/p/9996884.html
SpringBoot基礎系列-使用Profile
概述
Profile主要用於區分不同的環境。
使用方法
@Profile
在某個類、或者方法上添加@Profile注解,指定具體的profile環境標簽,那么只又在該profile處於active的情況下該類,方法才會被加載、執行。
@Profile({"dev","test"})
public class Xxx{
@Profile({"dev"})
@Bean
public Xxx xxx(){
return new Xxx();
}
}
多環境配置
properties配置文件
使用properties配置文件實現多環境配置,只能通過添加多個application-{profile}.properties來實現。
比如:application-dev.properties,application-test.properties
YAML配置文件
使用YAML實現多環境配置要簡單的多,只需要一個文件即可,application.yml
在文件中使用---來區分多個環境,每個環境都需要配置spring.profile屬性,不配置的屬於默認環境
server:
port: 8080
#屬性映射測試
app:
name: springdemo
size: 100M
user: weiyihaoge
version: 0.0.1
---
spring:
profiles: dev
server:
port: 8081
---
spring:
profiles: test
server:
port: 8082
---
spring:
profiles: pro
server:
port: 8083
激活profiles
可以在命令行參數、系統參數、application.properties等處進行配置
命令行
--spring.profiles.active=dev
application.properties
spring.profiles.active=dev
添加profiles
我們可以在不修改已啟動的profiles的基礎上添加新的profiles
使用spring.profiles.include屬性進行配置
還可以使用編程的方式實現,使用如下的方式添加:
SpringApplication.setAdditionalProfiles("development");
