Spring Boot中的Properties的使用详解
作者:flydean 发布时间:2021-07-02 07:25:22
简介
本文我们将会讨怎么在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;
@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,我们也可以使用类似的功能:
@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
如果我们有一组属性,想将这些属性封装成一个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将会自动将这些属性文件映射成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/instance
username: foo
password: bar
secret: foo
注意yaml文件不能用在@PropertySource中。如果你使用@PropertySource,则必须指定properties文件。
Properties环境变量
我们可以这样传入property环境变量:
java -jar app.jar --property="value"
~~shell
java -Dproperty.name="value" -jar app.jar
或者这样:
export name=value
java -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](https://github.com/ddean2009/learn-springboot2/tree/master/springboot-properties
来源:https://segmentfault.com/a/1190000021714088
猜你喜欢
- 这篇文章主要介绍了spring cloud gateway请求跨域问题解决方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定
- 前言最近对 base-spring-boot 项目进行了升级。在将其用于应用开发中时遇到java.lang.ArrayStoreE
- 1、首先 当然是启动genymotion2、然后Tomcat ,启动tomcat。。如图将请求的URL地址变为10.0.3.2 ,比如在电脑
- 面向对象语言对事物的体现都是以对象的形式,所以为了方便对多个对象的操作,就对对象进行存储,集合就是存储对象最常用的一种方式。数组虽然也可以存
- Threadlocal有什么用:简单的说就是,一个ThreadLocal在一个线程中是共享的,在不同线程之间又是隔离的(每个线程都只能看到自
- WPF的InkCanvas就是一个画板,可以在上面随意涂鸦,每写上一笔,InkCanvas的Strokes集合里就新增一个涂鸦对象,下面的代
- 前几天写了一篇《SpringBoot如何统一后端返回格式?老鸟们都是这样玩的!》阅读效果还不错,而且被很多号主都转载过,今天我们继续第二篇,
- 今天老师想让我帮忙把她们200多张寸照换成白底的,这些寸照里面多为蓝色底,红色底。用ps?不!用java!!对,我第一反应就是用java,到
- 相信大家在小的时候都玩过拼图游戏,现如今,手机普及,能在手机上玩的游戏越来越多,于是乎,重温小时候,编写这个简易拼图游戏,而且也能进一步加深
- 配置两个parent的方法在向pom.xml 文件中添加依赖之前需要先添加spring-boot-starter-parent。spring
- spring拓展 定义自己的namespace1.查看源码认识spring是怎么加载xml配置的1.1 spring是怎么创建对象的? 查看
- @Cacheable在同一类中方法调用无效上述图片中,同一个类中genLiveBullets()方法调用同类中的queryLiveByRoo
- 按照官方文档进行的配置:快速开始|mybatis-plus引入依赖:<!-- 引入mybatisPlus --> &
- 1、需要引入依赖<dependency> &l
- 前言 在软件开发中,我们通常会遇到一种场景,比如某个请求,会依次经过系统中的很多个模块来处理,如果某个模
- 首先看如下代码示例:System.out.println(0.05 + 0.01);System.out.println(0.05 - 0.
- 在 WinForms 中,有时要执行耗时的操作,在该操作未完成之前操作用户界面,会导致用户界面停止响应。解决的方法就是新开一个线程,把耗时的
- 前言进入到 SpringBoot2.7 时代,有小伙伴发现有一个常用的类忽然过期了:在 Spring Security 时代,这个类可太重要
- 今天我们来看一下在C#中对象序列化XML的方法。不得不说,在这个Json横行的年代,XML虽然式微,但也的确是一股子清流。(个人感觉)不多说
- 前段时间因为看JUC的源码,里面有大量关于unsafe的操作,所以就来看看了.写点笔记总结下(本文基于jdk1.8):unsafe可以帮我们