javascript
Spring Boot中的Properties
文章目錄
- 簡介
- 使用注解注冊一個Properties文件
- 使用屬性文件
- Spring Boot中的屬性文件
- @ConfigurationProperties
- yaml文件
- Properties環境變量
- java代碼配置
Spring Boot中的Properties
簡介
本文我們將會討怎么在Spring Boot中使用Properties。使用Properties有兩種方式,一種是java代碼的注解,一種是xml文件的配置。本文將會主要關注java代碼的注解。
使用注解注冊一個Properties文件
注冊Properties文件我們可以使用@PropertySource 注解,該注解需要配合@Configuration 一起使用。
@Configuration @PropertySource("classpath:foo.properties") public class PropertiesWithJavaConfig {//... }我們也可以使用placeholder來動態選擇屬性文件:
@PropertySource({ "classpath:persistence-${envTarget:mysql}.properties" })@PropertySource也可以多次使用來定義多個屬性文件:
@PropertySource("classpath:foo.properties") @PropertySource("classpath:bar.properties") public class PropertiesWithJavaConfig {//... }我們也可以使用@PropertySources來包含多個@PropertySource:
@PropertySources({@PropertySource("classpath:foo.properties"),@PropertySource("classpath:bar.properties") }) public class PropertiesWithJavaConfig {//... }使用屬性文件
最簡單直接的使用辦法就是使用@Value注解:
@Value( "${jdbc.url}" ) private String jdbcUrl;我們也可以給屬性添加默認值:
@Value( "${jdbc.url:aDefaultUrl}" ) private String jdbcUrl;如果要在代碼中使用屬性值,我們可以從Environment API中獲取:
@Autowired private Environment env; ... dataSource.setUrl(env.getProperty("jdbc.url"));Spring Boot中的屬性文件
默認情況下Spring Boot 會讀取application.properties文件作為默認的屬性文件。當然,我們也可以在命令行提供一個不同的屬性文件:
java -jar app.jar --spring.config.location=classpath:/another-location.properties如果是在測試環境中,我們可以使用@TestPropertySource 來指定測試的屬性文件:
@RunWith(SpringRunner.class) @TestPropertySource("/foo.properties") public class FilePropertyInjectionUnitTest {@Value("${foo}")private String foo;@Testpublic void whenFilePropertyProvided_thenProperlyInjected() {assertThat(foo).isEqualTo("bar");} }除了屬性文件,我們也可以直接以key=value的形式:
@RunWith(SpringRunner.class) @TestPropertySource(properties = {"foo=bar"}) public class PropertyInjectionUnitTest {@Value("${foo}")private String foo;@Testpublic void whenPropertyProvided_thenProperlyInjected() {assertThat(foo).isEqualTo("bar");} }使用@SpringBootTest,我們也可以使用類似的功能:
@RunWith(SpringRunner.class) @SpringBootTest(properties = {"foo=bar"}, classes = SpringBootPropertiesTestApplication.class) public class SpringBootPropertyInjectionIntegrationTest {@Value("${foo}")private String foo;@Testpublic void whenSpringBootPropertyProvided_thenProperlyInjected() {assertThat(foo).isEqualTo("bar");} }@ConfigurationProperties
如果我們有一組屬性,想將這些屬性封裝成一個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=barSpring Boot將會自動將這些屬性文件映射成java bean的屬性,我們需要做的就是定義好prefix。
yaml文件
Spring Boot也支持yaml形式的文件,yaml對于層級屬性來說更加友好和方便,我們可以看下properties文件和yaml文件的對比:
database.url=jdbc:postgresql:/localhost:5432/instance database.username=foo database.password=bar secret: foo database:url: jdbc:postgresql:/localhost:5432/instanceusername: foopassword: bar secret: foo注意yaml文件不能用在@PropertySource中。如果你使用@PropertySource,則必須指定properties文件。
Properties環境變量
我們可以這樣傳入property環境變量:
java -jar app.jar --property="value"~~shell
java -Dproperty.name=“value” -jar app.jar
環境變量有什么用呢? 當指定了特定的環境變量時候,Spring Boot會自動去加載application-environment.properties文件,Spring Boot默認的屬性文件也會被加載,只不過優先級比較低。
java代碼配置
除了注解和默認的屬性文件,java也可以使用PropertySourcesPlaceholderConfigurer來在代碼中顯示加載:
@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; }本文的例子可以參考:https://github.com/ddean2009/learn-springboot2/tree/master/springboot-properties
更多精彩內容且看:
- 區塊鏈從入門到放棄系列教程-涵蓋密碼學,超級賬本,以太坊,Libra,比特幣等持續更新
- Spring Boot 2.X系列教程:七天從無到有掌握Spring Boot-持續更新
- Spring 5.X系列教程:滿足你對Spring5的一切想象-持續更新
- java程序員從小工到專家成神之路(2020版)-持續更新中,附詳細文章教程
更多教程請參考 flydean的博客
總結
以上是生活随笔為你收集整理的Spring Boot中的Properties的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring Boot的TestRest
- 下一篇: SpringBoot @Configur