Spring Boot中的Properties

文章目录

Spring Boot中的Properties

简介

本文我们将会讨怎么在Spring Boot中使用Properties。使用Properties有两种方式,一种是java代码的注解,一种是xml文件的配置。本文将会主要关注java代码的注解。

使用注解注册一个Properties文件

注册Properties文件我们可以使用@PropertySource 注解,该注解需要配合@Configuration 一起使用。

1@Configuration 2@PropertySource("classpath:foo.properties") 3public class PropertiesWithJavaConfig { 4 //... 5}

我们也可以使用placeholder来动态选择属性文件:

1@PropertySource({ 2 "classpath:persistence-${envTarget:mysql}.properties" 3})

@PropertySource也可以多次使用来定义多个属性文件:

1@PropertySource("classpath:foo.properties") 2@PropertySource("classpath:bar.properties") 3public class PropertiesWithJavaConfig { 4 //... 5}

我们也可以使用@PropertySources来包含多个@PropertySource:

1@PropertySources({ 2 @PropertySource("classpath:foo.properties"), 3 @PropertySource("classpath:bar.properties") 4}) 5public class PropertiesWithJavaConfig { 6 //... 7}

使用属性文件

最简单直接的使用办法就是使用@Value注解:

1@Value( "${jdbc.url}" ) 2private String jdbcUrl;

我们也可以给属性添加默认值:

1@Value( "${jdbc.url:aDefaultUrl}" ) 2private String jdbcUrl;

如果要在代码中使用属性值,我们可以从Environment API中获取:

1@Autowired 2private Environment env; 3... 4dataSource.setUrl(env.getProperty("jdbc.url"));

Spring Boot中的属性文件

默认情况下Spring Boot 会读取application.properties文件作为默认的属性文件。当然,我们也可以在命令行提供一个不同的属性文件:

java -jar app.jar --spring.config.location=classpath:/another-location.properties

如果是在测试环境中,我们可以使用@TestPropertySource 来指定测试的属性文件:

1@RunWith(SpringRunner.class) 2@TestPropertySource("/foo.properties") 3public class FilePropertyInjectionUnitTest { 4 5 @Value("${foo}") 6 private String foo; 7 8 @Test 9 public void whenFilePropertyProvided_thenProperlyInjected() { 10 assertThat(foo).isEqualTo("bar"); 11 } 12}

除了属性文件,我们也可以直接以key=value的形式:

1@RunWith(SpringRunner.class) 2@TestPropertySource(properties = {"foo=bar"}) 3public class PropertyInjectionUnitTest { 4 5 @Value("${foo}") 6 private String foo; 7 8 @Test 9 public void whenPropertyProvided_thenProperlyInjected() { 10 assertThat(foo).isEqualTo("bar"); 11 } 12}

使用@SpringBootTest,我们也可以使用类似的功能:

1@RunWith(SpringRunner.class) 2@SpringBootTest(properties = {"foo=bar"}, classes = SpringBootPropertiesTestApplication.class) 3public class SpringBootPropertyInjectionIntegrationTest { 4 5 @Value("${foo}") 6 private String foo; 7 8 @Test 9 public void whenSpringBootPropertyProvided_thenProperlyInjected() { 10 assertThat(foo).isEqualTo("bar"); 11 } 12}

@ConfigurationProperties

如果我们有一组属性,想将这些属性封装成一个bean,则可以考虑使用@ConfigurationProperties。

1@ConfigurationProperties(prefix = "database") 2public class Database { 3 String url; 4 String username; 5 String password; 6 7 // standard getters and setters 8}

属性文件如下:

1database.url=jdbc:postgresql:/localhost:5432/instance 2database.username=foo 3database.password=bar

Spring Boot将会自动将这些属性文件映射成java bean的属性,我们需要做的就是定义好prefix。

yaml文件

Spring Boot也支持yaml形式的文件,yaml对于层级属性来说更加友好和方便,我们可以看下properties文件和yaml文件的对比:

1database.url=jdbc:postgresql:/localhost:5432/instance 2database.username=foo 3database.password=bar 4secret: foo 5 6database: 7 url: jdbc:postgresql:/localhost:5432/instance 8 username: foo 9 password: bar 10secret: foo

注意yaml文件不能用在@PropertySource中。如果你使用@PropertySource,则必须指定properties文件。

Properties环境变量

我们可以这样传入property环境变量:

java -jar app.jar --property="value"

~~shell
java -Dproperty.name=“value” -jar app.jar

1或者这样: 2 3~~~shell 4export name=value 5java -jar app.jar

环境变量有什么用呢? 当指定了特定的环境变量时候,Spring Boot会自动去加载application-environment.properties文件,Spring Boot默认的属性文件也会被加载,只不过优先级比较低。

java代码配置

除了注解和默认的属性文件,java也可以使用PropertySourcesPlaceholderConfigurer来在代码中显示加载:

1@Bean 2public static PropertySourcesPlaceholderConfigurer properties(){ 3 PropertySourcesPlaceholderConfigurer pspc 4 = new PropertySourcesPlaceholderConfigurer(); 5 Resource[] resources = new ClassPathResource[ ] 6 { new ClassPathResource( "foo.properties" ) }; 7 pspc.setLocations( resources ); 8 pspc.setIgnoreUnresolvablePlaceholders( true ); 9 return pspc; 10}

本文的例子可以参考:https://github.com/ddean2009/learn-springboot2/tree/master/springboot-properties

更多教程请参考 flydean的博客

点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )