SpringBoot 教程之属性加载详解
免费Java高级资料需要自己领取,涵盖了Java、Redis、MongoDB、MySQL、Zookeeper、Spring Cloud、Dubbo高并发分布式等教程,一共30G。
传送门:https://mp.weixin.qq.com/s/JzddfH-7yNudmkjT0IRL8Q
目录
- 加载 property 顺序
- 随机属性
- 命令行属性
- Application 属性文件
- Profile 特定属性
- 属性中的占位符
- YAML 属性
- 访问属性
- 多 profile 配置
- YAML 的缺点
- 属性前缀
- 属性松散绑定规则
- 属性转换
- 时间单位转换
- 数据大小转换
- 校验属性
加载 property 顺序
Spring Boot 加载 property 顺序如下:
- Devtools 全局配置 (当 devtools 被激活
\~/.spring-boot-devtools.properties). - ="https://docs.spring.io/spring/docs/5.1.3.RELEASE/javadoc-api/org/springframework/test/context/TestPropertySource.html">测试环境中的 @TestPropertySource 注解配置
- 测试环境中的属性
properties:@SpringBootTest和 测试注解. - 命令行参数
SPRING_APPLICATION_JSON属性ServletConfig初始化参数ServletContext初始化参数- JNDI attributes from 通过
java:comp/env配置的 JNDI 属性 - Java 系统属性 (
System.getProperties()) - 操作系统环境比那里
RandomValuePropertySource加载random.*形式的属性- jar 包外的
application-{profile}.properties或application-{profile}.yml配置 - jar 包内的
application-{profile}.properties或application-{profile}.yml配置 - jar 包外的
application.properties或application.yml配置 - jar 包内的
application.properties或application.yml配置 @PropertySource绑定的配置- 默认属性 (通过
SpringApplication.setDefaultProperties指定)
随机属性
RandomValuePropertySource 类用于配置随机值。
示例:
my.secret=${random.value}
my.number=${random.int}
my.bignumber=${random.long}
my.uuid=${random.uuid}
my.number.less.than.ten=${random.int(10)}
my.number.in.range=${random.int[1024,65536]}
命令行属性
默认情况下, SpringApplication 会获取 -- 参数(例如 --server.port=9000 ),并将这个 property 添加到 Spring 的 Environment 中。
如果不想加载命令行属性,可以通过 SpringApplication.setAddCommandLineProperties(false)禁用。
Application 属性文件
SpringApplication 会自动加载以下路径下的 application.properties 配置文件,将其中的属性读到 Spring 的 Environment 中。
- 当前目录的
/config子目录 - 当前目录
- classpath 路径下的
/configpackage - classpath 根路径
注:
以上列表的配置文件会根据顺序,后序的配置会覆盖前序的配置。
你可以选择 YAML(yml) 配置文件替换 properties 配置文件。
如果不喜欢 application.properties 作为配置文件名,可以使用 spring.config.name 环境变量替换:
$ java -jar myproject.jar --spring.config.name=myproject
可以使用 spring.config.location 环境变量指定配置文件路径:
$ java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties
Profile 特定属性
如果定义 application-{profile}.properties 形式的配置文件,将被视为 profile 环境下的特定配置。
可以通过 spring.profiles.active 参数来激活 profile,如果没有激活的 profile,默认会加载 application-default.properties 中的配置。
属性中的占位符
application.properties 中的值会被 Environment 过滤,所以,可以引用之前定义的属性。
app.name=MyApp
app.description=${app.name} is a Spring Boot application
注:你可以使用此技术来创建 Spring Boot 属性变量。请参考: Section 77.4, “Use ‘Short’ Command Line Arguments
YAML 属性
Spring Framework provides two convenient classes that can be used to load YAML documents. The YamlPropertiesFactoryBean loads YAML as Properties and the YamlMapFactoryBean loads YAML as a Map.
Spring 框架有两个类支持加载 YAML 文件。
YamlPropertiesFactoryBean将 YAML 文件的配置加载为Properties。YamlMapFactoryBean将 YAML 文件的配置加载为Map。
示例 1
environments:
dev:
url: http://dev.example.com
name: Developer Setup
prod:
url: http://another.example.com
name: My Cool App
等价于:
environments.dev.url=http://dev.example.com
environments.dev.name=Developer Setup
environments.prod.url=http://another.example.com
environments.prod.name=My Cool App
YAML 支持列表形式,等价于 property 中的 [index] :
my:
servers:
- dev.example.com
- another.example.com
等价于
my.servers[0]=dev.example.com
my.servers[1]=another.example.com
访问属性
YamlPropertySourceLoader 类会将 YAML 配置转化为 Spring Environment 类中的 PropertySource 。然后,你可以如同 properties 文件中的属性一样,使用 @Value 注解来访问 YAML 中配置的属性。
多 profile 配置
server:
address: 192.168.1.100
---
spring:
profiles: development
server:
address: 127.0.0.1
---
spring:
profiles: production & eu-central
server:
address: 192.168.1.120
YAML 的缺点
注:YAML 注解中的属性不能通过 @PropertySource 注解来访问。所以,如果你的项目中使用了一些自定义属性文件,建议不要用 YAML。
属性前缀
package com.example; import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List; import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties(prefix="acme")
public class AcmeProperties { private boolean enabled; private InetAddress remoteAddress; private final Security security = new Security(); public boolean isEnabled() { ... } public void setEnabled(boolean enabled) { ... } public InetAddress getRemoteAddress() { ... } public void setRemoteAddress(InetAddress remoteAddress) { ... } public Security getSecurity() { ... } public static class Security { private String username; private String password; private List<String> roles = new ArrayList<>(Collections.singleton("USER")); public String getUsername() { ... } public void setUsername(String username) { ... } public String getPassword() { ... } public void setPassword(String password) { ... } public List<String> getRoles() { ... } public void setRoles(List<String> roles) { ... } }
}
相当于支持配置以下属性:
acme.enabledacme.remote-addressacme.security.usernameacme.security.passwordacme.security.roles
然后,你需要使用 @EnableConfigurationProperties 注解将属性类注入配置类中。
@Configuration
@EnableConfigurationProperties(AcmeProperties.class)
public class MyConfiguration {
}
属性松散绑定规则
Spring Boot 属性名绑定比较松散。
以下属性 key 都是等价的:
PropertyNoteacme.my-project.person.first-name-分隔acme.myProject.person.firstName驼峰命名acme.my_project.person.first_name_分隔ACME_MYPROJECT_PERSON_FIRSTNAME大写字母
属性转换
如果需要类型转换,你可以提供一个 ConversionService bean (一个名叫 conversionService的 bean) 或自定义属性配置 (一个 CustomEditorConfigurer bean) 或自定义的 Converters (被 @ConfigurationPropertiesBinding 注解修饰的 bena)。
时间单位转换
Spring 使用 java.time.Duration 类代表时间大小,以下场景适用:
- 除非指定
@DurationUnit,否则一个 long 代表的时间为毫秒。 - ISO-8601 标准格式(
java.time.Duration的实现就是参照此标准) - 你也可以使用以下支持的单位:
ns- 纳秒us- 微秒ms- 毫秒s- 秒m- 分h- 时d- 天
示例:
@ConfigurationProperties("app.system")
public class AppSystemProperties {
@DurationUnit(ChronoUnit.SECONDS)
private Duration sessionTimeout = Duration.ofSeconds(30);
private Duration readTimeout = Duration.ofMillis(1000);
public Duration getSessionTimeout() {
return this.sessionTimeout;
}
public void setSessionTimeout(Duration sessionTimeout) {
this.sessionTimeout = sessionTimeout;
}
public Duration getReadTimeout() {
return this.readTimeout;
}
public void setReadTimeout(Duration readTimeout) {
this.readTimeout = readTimeout;
}
}
数据大小转换
Spring 使用 DataSize 类代表数据大小,以下场景适用:
- long 值(默认视为 byte)
- 你也可以使用以下支持的单位:
BKBMBGBTB
示例:
@ConfigurationProperties("app.io")
public class AppIoProperties {
@DataSizeUnit(DataUnit.MEGABYTES)
private DataSize bufferSize = DataSize.ofMegabytes(2);
private DataSize sizeThreshold = DataSize.ofBytes(512);
public DataSize getBufferSize() {
return this.bufferSize;
}
public void setBufferSize(DataSize bufferSize) {
this.bufferSize = bufferSize;
}
public DataSize getSizeThreshold() {
return this.sizeThreshold;
}
public void setSizeThreshold(DataSize sizeThreshold) {
this.sizeThreshold = sizeThreshold;
}
}
校验属性
@ConfigurationProperties(prefix="acme")
@Validated
public class AcmeProperties { @NotNull
private InetAddress remoteAddress; @Valid
private final Security security = new Security(); // ... getters and setters public static class Security { @NotEmpty
public String username; // ... getters and setters } }
你也可以自定义一个名为 configurationPropertiesValidator 的校验器 Bean。获取这个 @Bean 的方法必须声明为 static。
使用方法:
mvn clean package
cd target
java -jar sbe-core-property.jar
SpringBoot 教程之属性加载详解的更多相关文章
- Javascript 异步加载详解
Javascript 异步加载详解 本文总结一下浏览器在 javascript 的加载方式. 关键词:异步加载(async loading),延迟加载(lazy loading),延迟执行(lazy ...
- Javascript图片预加载详解
预加载图片是提高用户体验的一个很好方法.图片预先加载到浏览器中,访问者便可顺利地在你的网站上冲浪,并享受到极快的加载速度.这对图片画廊及图片占据很大比例的网站来说十分有利,它保证了图片快速.无缝地发布 ...
- Javascript 异步加载详解(转)
本文总结一下浏览器在 javascript 的加载方式. 关键词:异步加载(async loading),延迟加载(lazy loading),延迟执行(lazy execution),async 属 ...
- 单个SWF文件loading加载详解(转)
通过带宽查看器,可以看到SWF中每帧所占带宽状况.另外,我们还可以在Flash发布设置中,选择生成体积报告. 勾选这一项之后,发布flash时,会自动在fla目录中生成一个名为”文件名 Report. ...
- javascript异步加载详解(转)
本文总结一下浏览器在 javascript 的加载方式. 关键词:异步加载(async loading),延迟加载(lazy loading),延迟执行(lazy execution),async 属 ...
- 转:web前端面试题合集 (Javascript相关)(js异步加载详解)
1. HTTP协议的状态消息都有哪些? 1**:请求收到,继续处理2**:操作成功收到,分析.接受3**:完成此请求必须进一步处理4**:请求包含一个错误语法或不能完成5**:服务器执行一个完全有效请 ...
- js模块加载详解
看着java中各种import加载,在回过头来看看javascript还在自己造轮子,写各种XX的模块加载框架,ECMASCRIPT6不知什么时候能够普及.不过DT归DT,该学的还是要学. 一 同步加 ...
- ios 懒加载详解
iOS开发之懒加载 在iOS开发中几乎经常用到懒加载技术,比如我们存放网络数据的数组,控制器的view,控件的自定义,复杂的运算逻辑等等情况下都会用到懒加载技术,那么什么是懒加载呢?? 他又有什么样的 ...
- Javascript图片预加载详解 分类: JavaScript HTML+CSS 2015-05-29 11:01 768人阅读 评论(0) 收藏
预加载图片是提高用户体验的一个很好方法.图片预先加载到浏览器中,访问者便可顺利地在你的网站上冲浪,并享受到极快的加载速度.这对图片画廊及图片占据很大比例的网站来说十分有利,它保证了图片快速.无缝地发布 ...
随机推荐
- 阿里钉钉技术分享:企业级IM王者——钉钉在后端架构上的过人之处
本文引用了唐小智发表于InfoQ公众号上的“钉钉企业级IM存储架构创新之道”一文的部分内容,收录时有改动,感谢原作者的无私分享. 1.引言 业界的 IM 产品在功能上同质化较高,而企业级的 IM 产品 ...
- Appium+Java 自动化测试系列二:Maven+Testng
新建Maven项目作为测试项目分为3个步骤: 1.Eclipse安装Testng 插件 2.新建Maven项目 3.引入Testng 一.Eclipse安装Testng插件 TestNG安装可选择在线 ...
- Css 设置固定表格头部,内容可滚动
效果图:
- JavaScript定时器方法
一.setTimeout() 延迟性操作 window.setTimeout(function(){ console.log('派大星');//延迟了4秒 },4000); console.log(' ...
- 计算机网络知识(TCP连接,TCP/UDP区别,HTTP与HTTPS,Socket原理等等)
1.网络七层协议包含,物理层.数据链路层.网络层(ip协议).传输层(TCP传输控制协议.UDP用户数据报协议).会话层.表示层.应用层(http协议).是一个提供的概念架构协议. 2.TCP/IP协 ...
- PostgreSQL TIMESTAMP类型 时间戳
PostgreSQL 提供两种存储时间戳的数据类型: 不带时区的 TIMESTAMP 和带时区的 TIMESTAMPTZ. TIMESTAMP 数据类型可以同时存储日期和时间,但它不存储时区.这意味着 ...
- ArcGIS Server10.4 service发布步骤
准备内容 安装环境:win10*64位专业版 安装文件:ArcGIS_Server_Ent_Windows_1041_150998.iso 破解文件:Lic10.4.1.ecp #安装Server前, ...
- Good start is a half success(2019-04-07)
一. 回顾你过去将近3年的学习经历. (1)当初你报考的时候,是真正喜欢计算机这个专业吗?. (2)你现在后悔选择了这个专业吗?. (3)你认为你现在最喜欢的领域是什么(可以是计算机的也可以是其它领域 ...
- Saltstack_使用指南14_无master
1. 主机规划 salt 版本 [root@salt100 ~]# salt --version salt (Oxygen) [root@salt100 ~]# salt-minion --versi ...
- Paper慢慢读 - AB实验人群定向 Recursive Partitioning for Heterogeneous Casual Effects
这篇是treatment effect估计相关的论文系列第一篇所以会啰嗦一点多给出点背景. 论文 Athey, S., and Imbens, G. 2016. Recursive partition ...