Spring Boot中的Properties的使用詳解
簡(jiǎn)介
本文我們將會(huì)討怎么在Spring Boot中使用Properties。使用Properties有兩種方式,一種是java代碼的注解,一種是xml文件的配置。本文將會(huì)主要關(guān)注java代碼的注解。
使用注解注冊(cè)一個(gè)Properties文件
注冊(cè)Properties文件我們可以使用@PropertySource 注解,該注解需要配合@Configuration 一起使用。
@Configuration
@PropertySource("classpath:foo.properties")
public class PropertiesWithJavaConfig {
//...
}
我們也可以使用placeholder來(lái)動(dòng)態(tài)選擇屬性文件:
@PropertySource({
"classpath:persistence-${envTarget:mysql}.properties"
})
@PropertySource也可以多次使用來(lái)定義多個(gè)屬性文件:
@PropertySource("classpath:foo.properties")
@PropertySource("classpath:bar.properties")
public class PropertiesWithJavaConfig {
//...
}
我們也可以使用@PropertySources來(lái)包含多個(gè)@PropertySource:
@PropertySources({
@PropertySource("classpath:foo.properties"),
@PropertySource("classpath:bar.properties")
})
public class PropertiesWithJavaConfig {
//...
}
使用屬性文件
最簡(jiǎn)單直接的使用辦法就是使用@Value注解:
@Value( "${jdbc.url}" )
private String jdbcUrl;
我們也可以給屬性添加默認(rèn)值:
@Value( "${jdbc.url:aDefaultUrl}" )
private String jdbcUrl;
如果要在代碼中使用屬性值,我們可以從Environment API中獲?。?/p>
@Autowired
private Environment env;
...
dataSource.setUrl(env.getProperty("jdbc.url"));
Spring Boot中的屬性文件
默認(rèn)情況下Spring Boot 會(huì)讀取application.properties文件作為默認(rèn)的屬性文件。當(dāng)然,我們也可以在命令行提供一個(gè)不同的屬性文件:
java -jar app.jar --spring.config.location=classpath:/another-location.properties
如果是在測(cè)試環(huán)境中,我們可以使用@TestPropertySource 來(lái)指定測(cè)試的屬性文件:
@RunWith(SpringRunner.class)
@TestPropertySource("/foo.properties")
public class FilePropertyInjectionUnitTest {
@Value("${foo}")
private String foo;
@Test
public void whenFilePropertyProvided_thenProperlyInjected() {
assertThat(foo).isEqualTo("bar");
}
}
除了屬性文件,我們也可以直接以key=value的形式:
@RunWith(SpringRunner.class)
@TestPropertySource(properties = {"foo=bar"})
public class PropertyInjectionUnitTest {
@Value("${foo}")
private String foo;
@Test
public void whenPropertyProvided_thenProperlyInjected() {
assertThat(foo).isEqualTo("bar");
}
}
使用@SpringBootTest,我們也可以使用類(lèi)似的功能:
@RunWith(SpringRunner.class)
@SpringBootTest(properties = {"foo=bar"}, classes = SpringBootPropertiesTestApplication.class)
public class SpringBootPropertyInjectionIntegrationTest {
@Value("${foo}")
private String foo;
@Test
public void whenSpringBootPropertyProvided_thenProperlyInjected() {
assertThat(foo).isEqualTo("bar");
}
}
@ConfigurationProperties
如果我們有一組屬性,想將這些屬性封裝成一個(gè)bean,則可以考慮使用@ConfigurationProperties。
@ConfigurationProperties(prefix = "database")
public class Database {
String url;
String username;
String password;
// standard getters and setters
}
屬性文件如下:
database.url=jdbc:postgresql:/localhost:5432/instance database.username=foo database.password=bar
Spring Boot將會(huì)自動(dòng)將這些屬性文件映射成java bean的屬性,我們需要做的就是定義好prefix。
yaml文件
Spring Boot也支持yaml形式的文件,yaml對(duì)于層級(jí)屬性來(lái)說(shuō)更加友好和方便,我們可以看下properties文件和yaml文件的對(duì)比:
database.url=jdbc:postgresql:/localhost:5432/instance database.username=foo database.password=bar secret: foo
database: url: jdbc:postgresql:/localhost:5432/instance username: foo password: bar secret: foo
注意yaml文件不能用在@PropertySource中。如果你使用@PropertySource,則必須指定properties文件。
Properties環(huán)境變量
我們可以這樣傳入property環(huán)境變量:
java -jar app.jar --property="value"
~~shell
java -Dproperty.name="value" -jar app.jar
或者這樣:
export name=value
java -jar app.jar
環(huán)境變量有什么用呢? 當(dāng)指定了特定的環(huán)境變量時(shí)候,Spring Boot會(huì)自動(dòng)去加載application-environment.properties文件,Spring Boot默認(rèn)的屬性文件也會(huì)被加載,只不過(guò)優(yōu)先級(jí)比較低。
## java代碼配置
除了注解和默認(rèn)的屬性文件,java也可以使用PropertySourcesPlaceholderConfigurer來(lái)在代碼中顯示加載:
@Bean
public static PropertySourcesPlaceholderConfigurer properties(){
PropertySourcesPlaceholderConfigurer pspc
= new PropertySourcesPlaceholderConfigurer();
Resource[] resources = new ClassPathResource[ ]
{ new ClassPathResource( "foo.properties" ) };
pspc.setLocations( resources );
pspc.setIgnoreUnresolvablePlaceholders( true );
return pspc;
}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
詳解SpringCloud服務(wù)認(rèn)證(JWT)
本篇文章主要介紹了SpringCloud服務(wù)認(rèn)證(JWT),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-01-01
mybatis插入數(shù)據(jù)后返回自增主鍵ID的兩種實(shí)現(xiàn)方式
這篇文章主要介紹了mybatis插入數(shù)據(jù)后返回自增主鍵ID的兩種實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-05-05
spring的UnexpectedRollbackException事務(wù)嵌套示例解析
這篇文章主要為大家介紹了spring的UnexpectedRollbackException事務(wù)嵌套示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-09-09
Java遞歸實(shí)現(xiàn)斐波那契數(shù)列
這篇文章主要為大家詳細(xì)介紹了Java遞歸實(shí)現(xiàn)斐波那契數(shù)列,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-02-02
Java設(shè)計(jì)模式之策略模式_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
策略模式是對(duì)算法的封裝,把一系列的算法分別封裝到對(duì)應(yīng)的類(lèi)中,并且這些類(lèi)實(shí)現(xiàn)相同的接口,相互之間可以替換。接下來(lái)通過(guò)本文給大家分享Java設(shè)計(jì)模式之策略模式,感興趣的朋友一起看看吧2017-08-08
Java壓縮解壓zip技術(shù)_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
Java解壓縮zip - 多個(gè)文件(包括文件夾),對(duì)多個(gè)文件和文件夾進(jìn)行壓縮,對(duì)復(fù)雜的文件目錄進(jìn)行解壓。壓縮方法使用的是可變參數(shù),可以壓縮1到多個(gè)文件2017-05-05

