前言
通常我們開發不可能只有一個生產環境,還會有其它的開發,測試,預發布環境等等。為了更好的管理每個環境的配置項,springboot也提供了對應的環境隔離的方法。
直接上干貨
知識點
激活環境方法
1,在application.properties或者yaml文件中配置:spring.profiles.active=環境1,環境2
2,命令行激活:java -jar xxx.jar --spring.profiles.active=環境1,環境2
補充
1,修改默認環境名稱 spring.profiles.default=test;
2,不管激活哪個環境,這些環境都要有 spring.profiles.include= security ?總是要生效的環境
3,對多環境進行分組:spring.profiles.group.name(你自己起名)=環境1,環境2 ?
?? ?也可以這么寫spring.profiles.group.name[0]=環境1
?? ?spring.profiles.group.name[1]=環境2
使用則相同:spring.profiles.active=name(group起的名)
補充相關注解:@Profile()
@Profile("dev") => 注解表示這個類只能在這些環境下生效, 如果值為"default"則表示:默認環境
注意
命名規范:application-(profiles標識).properties
代碼測試
照例準備啟動類
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class Applications {public static void main(String[] args) {SpringApplication.run(Applications.class, args);}
}
準備配置文件application.properties
spring.profiles.active=devpro.b.value=b value in application
準備dev環境配置文件application-dev.properties
pro.a.value=this is dev
pro.b.value=b value in dev
testController類
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;@RestController
@Slf4j
public class ProfilesTestController {@Value("${pro.a.value}")private String a;@Value("${pro.b.value}")private String b;@RequestMapping(method = RequestMethod.GET, path = "/profiles/test")public void test1() {log.info("測試激活環境是否生效" + a);log.info("測試與application.properties中配置項沖突時,生效為哪個:" + b);}}
啟動測試,測試結果如圖所示
這里需要注意,盡可能不要去在不同的properties寫相同的配置,如果你的代碼中加了一些別的東西,例如常用的配置解密功能等操作property的功能時,會出現與預想結果之外的輸出。如下圖,我加入自定義解密之后的輸出。
希望對各位看官老爺有幫助,如果可以的話,能否請各位老爺點個贊,關注一下博主呢,在這里非常感謝各位老爺了。