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:1)开源框架2)IoC(控制反转),将类的创建和依赖关系写在配置文件里,由配置文件注入,实现了松耦合3)AOP 将安全,事务等
- 出于安全考虑,在后台与前台进行数据传输时,往往不会直接传输实体模型,而是使用Dto(Data transfer object 数据传输对象)
- 一、代理是Java常用的设计模式,代理类通过调用被代理类的相关方法,并对相关方法进行增强。加入一些非业务性代码,比如事务、日志、报警发邮件等
- vs2010测试通过,主要思想是由出生日期和当前日期,两个日期计算出年龄(岁、月、天)using System;using System.C
- 前言在一般能搜到的所有实现圆角窗体的示例中,都是通过绘制圆角的路径,并创建对应的窗体Region区域实现。目前所知,重新创建Region的所
- 1、SpringSecurity 本质是一个过滤器链SpringSecurity 采用的是责任链的设计模式,它有一条很长的过滤器链。现在对这
- 使用简单的fragment实现左侧导航,供大家参考,具体内容如下先上效果图:MainActivity.javapublic class Ma
- 写一个简单的mybatis plus插件自动生成代码的例子pom.xml 添加配置<!-- mybatis plus 插件-->
- 在Java5.0之前,只有synchronized(内置锁)和volatile. Java5.0后引入了显示锁ReentrantLock.R
- Spring MVC Controller控制器,是MVC中的部分C,为什么是部分呢?因为此处的控制器主要负责功能处理部分:收集、验证请求参
- Android中的消息处理机制大量依赖于Handler。每个Handler都有对应的Looper,用于不断地从对应的MessageQueue
- 一 模式介绍重试模式,是应用在异常处理中,发生异常的时候,能够对业务程序进行重新调用,在实际中,可以使用Polly提供稳定,简单的用法,自己
- 建造者模式是Java中一种创建型设计模式,它的主要目的是将一个复杂对象的构建过程分解为多个简单对象的构建过程,并且使这些构建过程按照一定的顺
- Android 中倒计时验证两种常用方式实例详解短信验证码功能,这里总结了两种常用的方式,可以直接拿来使用。看图:说明:这里的及时从10开始
- 上篇文章给大家介绍了springboot全局字符编码设置解决乱码问题 感兴趣的朋友可以点击查看,下面通过两种方式给大家介绍Spri
- SpringBoot配置外部静态资源映射使用场景实际项目中,特别是前后端分离的项目,SpringBoot后台打包(jar包)后,以jar包形
- 今天介绍一个自己做的快递单号查询的简单APP,供大家参考。由于需要使用http和json,本文在build.gradle(module:ap
- 1.kotlin的字符串操作和Java有些不同,有些新增。1)先看字符串比较java中==比较的是变量的引用是否指向同一个地址,Kotlin
- 1、背景当我们的hadoop集群运行了一段时间之后,各个DataNode上的数据分布并不一定是均匀分布的。比如说: 我们向现有集群中添加了一
- 前言最近在改进项目的并发功能,但开发起来磕磕碰碰的。看了好多资料,总算加深了认识。于是打算配合查看源代码,总结并发编程的原理。准备从用得最多