Spring Boot中的Properties
文章目录
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;
@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
或者这样:
~~~shell
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
更多教程请参考 flydean的博客
Spring Boot中的Properties的更多相关文章
- Spring Boot中application.properties和application.yml文件
application.properties和application.yml文件可以放在一下四个位置: 外置,在相对于应用程序运行目录的/congfig子目录里. 外置,在应用程序运行的目录里 内置, ...
- Spring Boot 中配置文件application.properties使用
一.配置文档配置项的调用(application.properties可放在resources,或者resources下的config文件夹里) package com.my.study.contro ...
- springboot(十一):Spring boot中mongodb的使用
mongodb是最早热门非关系数据库的之一,使用也比较普遍,一般会用做离线数据分析来使用,放到内网的居多.由于很多公司使用了云服务,服务器默认都开放了外网地址,导致前一阵子大批 MongoDB 因配置 ...
- Spring Boot Dubbo applications.properties 配置清单
摘要: 原创出处 www.bysocket.com 「泥瓦匠BYSocket 」欢迎转载,保留摘要,谢谢! 『 与其纠结,不如行动学习.Innovate ,And out execute ! 』 本文 ...
- 在Spring Boot中使用数据缓存
春节就要到了,在回家之前要赶快把今年欠下的技术债还清.so,今天继续.Spring Boot前面已经预热了n篇博客了,今天我们来继续看如何在Spring Boot中解决数据缓存问题.本篇博客是以初识在 ...
- 在Spring Boot中使用数据库事务
我们在前面已经分别介绍了如何在Spring Boot中使用JPA(初识在Spring Boot中使用JPA)以及如何在Spring Boot中输出REST资源(在Spring Boot中输出REST资 ...
- 在Spring Boot中输出REST资源
前面我们我们已经看了Spring Boot中的很多知识点了,也见识到Spring Boot带给我们的各种便利了,今天我们来看看针对在Spring Boot中输出REST资源这一需求,Spring Bo ...
- 初识在Spring Boot中使用JPA
前面关于Spring Boot的文章已经介绍了很多了,但是一直都没有涉及到数据库的操作问题,数据库操作当然也是我们在开发中无法回避的问题,那么今天我们就来看看Spring Boot给我们提供了哪些疯狂 ...
- Spring Boot 中的静态资源到底要放在哪里?
当我们使用 SpringMVC 框架时,静态资源会被拦截,需要添加额外配置,之前老有小伙伴在微信上问松哥Spring Boot 中的静态资源加载问题:"松哥,我的HTML页面好像没有样式?& ...
随机推荐
- 从 Linux 操作系统谈谈 IO 模型(终)
Linux 为什么要区分内核空间与用户空间? Linux 操作系统的 IO 模型有哪几种?有啥区别? 常说的阻塞现象,到底是咋回事? 网络编程研发时,那块到底耗时最多,代码是否还有优化空间? 前几期的 ...
- P1627 [CQOI2009]中位数 题解
CSDN同步 原题链接 简要题意: 给定一个 \(1\) ~ \(n\) 的排列,求以 \(b\) 为中位数的 连续子序列且长度为奇数 的个数. 显然这段序列包含 \(b\). 中位数的定义:排序后在 ...
- MyBatis 学习笔记(1)
MyBatis 的基本构成 SqlSessionFactoryBuilder(构造器):它会根据配置信息或者代码来生成 SqlSessionFactory(工厂接口) SqlSessionFactor ...
- 个推push数据统计(爬虫)
该方案基于任务调度框架Gearman,采用Python开发的分布式数据统计系统. 项目的目录结构很简单: # apple at localhost in ~/Develop/getui [11:24: ...
- "高亮显示"组件:<mark> —— 快应用组件库H-UI
 <import name="mark" src="../Common/ui/h-ui/text/c_tag_mark"></import& ...
- "文字链接"组件:<h-link> —— 快应用组件库H-UI
 <import name="h-link" src="../Common/ui/h-ui/basic/c_link"></import&g ...
- C# 发布时出现:在与 SQL Server 建立连接时出现与网络相关的或特定于实例的错误
在与 SQL Server 建立连接时出现与网络相关的或特定于实例的错误.未找到或无法访问服务器.请验证实例名称是否正确并且 SQL Server 已配置为允许远程连接. (provider: SQL ...
- java网络编程socket\server\TCP笔记(转)
java网络编程socket\server\TCP笔记(转) 2012-12-14 08:30:04| 分类: Socket | 标签:java |举报|字号 订阅 1 TCP的开销 a ...
- 013-结构体-C语言笔记
013-结构体-C语言笔记 学习目录 1.[掌握]返回指针的函数 2.[掌握]指向函数的指针 3.[掌握]结构体的声明 4.[掌握]结构体与数组 5.[掌握]结构体与指针 6.[掌握]结构体的嵌套 7 ...
- 设计模式中巧记I/O
一.I/O 1. I/O操作中的设计模式 概要 以设计模式角度,自顶向下理解I/O源码结构 理解字节与字符的关系 1.1 装饰者模式(输入流为例) 背景:通过继承扩展对象耦合度高,使用装饰者扩展可以在 ...