Spring Boot的配置方式
Spring Boot中遵循了約定優(yōu)于配置
的原則尚卫,故我們在構(gòu)建Spring Boot Application時非常輕松箱叁。在實(shí)際生產(chǎn)過程中父款,我們需要針對工程做額外的配置轻纪,那么我們該怎么使用額外的配置呢烹植?
Spring Boot允許使用外部化配置,以便我們可以在不同的環(huán)境中使用相同的應(yīng)用程序代碼窖贤。 這些配置可以使用屬性文件砖顷,YAML文件贰锁,環(huán)境變量和命令行參數(shù)等來外化配置。 屬性值可以使用@Value
注釋直接注入到bean中滤蝠,通過Spring的Environment抽象訪問或通過@ConfigurationProperties
綁定到結(jié)構(gòu)化對象豌熄。
Spring Boot使用一個非常特殊的PropertySource順序,該順序被設(shè)計為允許對值進(jìn)行明智的重寫物咳。 屬性按以下順序考慮:
Devtools global settings properties on your home directory (
~/.spring-boot-devtools.properties
when devtools is active).@TestPropertySource
annotations on your tests.@SpringBootTest#properties
annotation attribute on your tests.Command line arguments.
Properties from
SPRING_APPLICATION_JSON
(inline JSON embedded in an environment variable or system property)ServletConfig
init parameters.ServletContext
init parameters.JNDI attributes from
java:comp/env
.Java System properties (
System.getProperties()
).OS environment variables.
A
RandomValuePropertySource
that only has properties inrandom.*
.Profile-specific application properties outside of your packaged jar (
application-{profile}.properties
and YAML variants)Profile-specific application properties packaged inside your jar (
application-{profile}.properties
and YAML variants)Application properties outside of your packaged jar (
application.properties
and YAML variants).Application properties packaged inside your jar (
application.properties
and YAML variants).@PropertySource
annotations on your@Configuration
classes.Default properties (specified using
SpringApplication.setDefaultProperties
).
本文主要討論在application.properties
配置文件中來進(jìn)行額外的配置锣险,其他的使用配置的方法詳情參考這里。
application.properties文件的使用
SpringApplication將從以下位置的application.properties
文件加載屬性览闰,并將它們添加到Spring環(huán)境:
- 當(dāng)前路徑下的/config子目錄芯肤。
- 當(dāng)前路徑。
- classpath路徑下的/config子路徑压鉴。
- classpath路徑
列表按優(yōu)先級排序(在列表中較高的位置定義的屬性覆蓋在較低位置定義的屬性)崖咨。
在上文的程序中,在resources
目錄添加application.properties
文件油吭,添加如下配置
#tomcat端口號
server.port=8888
啟動Spring Boot程序击蹲,此時我們訪問程序的端口號就變?yōu)榱?888。
更多application.properties
的配置婉宰,請參考官方文檔歌豺。
本文示例程序請點(diǎn)此獲取。
詳細(xì)資料請參考Spring Boot官網(wǎng)心包。