畢設(shè)網(wǎng)站可以用axure做嗎軟文營銷怎么寫
文章目錄
- SpringBoot 的多配置文件
- spring.profiles.active 配置
- @Profile 和 @ActiveProfiles 注解
SpringBoot 的多配置文件
spring.profiles.active 配置
默認(rèn)情況下,當(dāng)你啟動 SpringBoot 項(xiàng)目時,會在日志中看到如下一條 INFO 信息:
No active profile set, falling back to default profiles: default
這條消息是在告訴你,由于你沒有激活、啟用某個配置文件,SpringBoot 使用了默認(rèn)的配置文件,也就是 application.properties
或 application.yml
。當(dāng)然,這并不是什么錯誤。
SpringBoot 允許我們的項(xiàng)目提供多配置文件,并『激活、啟用』其中的某一個。這些配置文件的命名規(guī)則為:application-xxx.properties
或 application-xxx.yml
。
提供多個配置文件之后,你在 SpringBoot 默認(rèn)加載的配置文件 application.properties 或 application.yml 中只用寫一個配置項(xiàng),用以激活、啟用某個 .properties 或 .yml 即可。例如:
spring:profiles:active: dev
上例中的 dev
就是 application-xxx.properties
或 application-xx.yml
中的那個 xxx 。
現(xiàn)在你再啟動 SpringBoot,你會看到如下的 INFO 信息:
The following profiles are active: dev
這表示 SpringBoot 本次啟動使用的就是這個配置文件。
@Profile 和 @ActiveProfiles 注解
了解
@Profile 注解配合 spring.profiles.active
參數(shù),也可以實(shí)現(xiàn)不同環(huán)境下(開發(fā)、測試、生產(chǎn))配置參數(shù)的切換。
另外,@ActiveProfiles 注解(在測試環(huán)境中)可以起到 spring.profiles.active
參數(shù)的作用。
@Configuration
public class MyConfiguration {@Bean@Profile("xxx")public Human tommy() {return new Human("tom", 20);}@Bean@Profile("yyy")public Human jerry() {return new Human("jerry", 19);}}
在上面的配置中:
- 存在 2 套配置:
xxx
和yyy
; - name 為
tommy
的 Human Bean 僅存在于xxx
的配置套餐中; - name 為
jerry
的 Human Bean 僅存在于yyy
的配置套餐中;
在 application.yml 配置文件通過 active 配置激活啟動一個:
spring:profiles:active: yyy
我們可以在 JUnit 中驗(yàn)證結(jié)果:
@SpringBootTest
class AppTest {@Autowiredprivate Human human;@Testpublic void demo() {System.out.println(human); // 這里輸出的是 jerry Human Bean}
}
在測試類的使用中,你也可以將 application.yml 中的 active 配置項(xiàng)去掉,轉(zhuǎn)而在測試類的頭上使用 @ActiveProfiles 注解,也能起到同樣效果:
@SpringBootTest
ActiveProfiles(profiles = "xxx")
class AppTest {...
}