加载 property 顺序

Spring Boot 加载 property 顺序如下:

  1. Devtools 全局配置 (当 devtools 被激活 \~/.spring-boot-devtools.properties).
  2. 测试环境中的 @TestPropertySource 注解配置
  3. 测试环境中的属性 properties@SpringBootTest测试注解.
  4. 命令行参数
  5. SPRING_APPLICATION_JSON 属性
  6. ServletConfig 初始化参数
  7. ServletContext 初始化参数
  8. JNDI attributes from 通过 java:comp/env 配置的 JNDI 属性
  9. Java 系统属性 (System.getProperties())
  10. 操作系统环境比那里
  11. RandomValuePropertySource 加载 random.* 形式的属性
  12. jar 包外的 application-{profile}.propertiesapplication-{profile}.yml 配置
  13. jar 包内的 application-{profile}.propertiesapplication-{profile}.yml 配置
  14. jar 包外的 application.propertiesapplication.yml 配置
  15. jar 包内的 application.propertiesapplication.yml 配置
  16. @PropertySource 绑定的配置
  17. 默认属性 (通过 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 中。

  1. 当前目录的 /config 子目录
  2. 当前目录
  3. classpath 路径下的 /config package
  4. 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.enabled
  • acme.remote-address
  • acme.security.username
  • acme.security.password
  • acme.security.roles

然后,你需要使用 @EnableConfigurationProperties 注解将属性类注入配置类中。

@Configuration
@EnableConfigurationProperties(AcmeProperties.class)
public class MyConfiguration {
}

属性松散绑定规则

Spring Boot 属性名绑定比较松散。

以下属性 key 都是等价的:

Property Note
acme.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)
  • 你也可以使用以下支持的单位:
    • B
    • KB
    • MB
    • GB
    • TB

示例:

@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

示例源码

示例源码:spring-boot-property

参考资料

Spring Boot 之属性读写详解的更多相关文章

  1. Spring Boot 之使用 Json 详解

    Spring Boot 之使用 Json 详解 简介 Spring Boot 支持的 Json 库 Spring Web 中的序列化.反序列化 指定类的 Json 序列化.反序列化 @JsonTest ...

  2. Spring Boot(八):RabbitMQ详解

    Spring Boot(八):RabbitMQ详解 RabbitMQ 即一个消息队列,主要是用来实现应用程序的异步和解耦,同时也能起到消息缓冲,消息分发的作用. 消息中间件在互联网公司的使用中越来越多 ...

  3. Spring boot注解(annotation)含义详解

    Spring boot注解(annotation)含义详解 @Service用于标注业务层组件@Controller用于标注控制层组件(如struts中的action)@Repository用于标注数 ...

  4. Spring Boot Actuator监控使用详解

    在企业级应用中,学习了如何进行SpringBoot应用的功能开发,以及如何写单元测试.集成测试等还是不够的.在实际的软件开发中还需要:应用程序的监控和管理.SpringBoot的Actuator模块实 ...

  5. Spring Boot中@ConditionalOnProperty使用详解

    在Spring Boot的自动配置中经常看到@ConditionalOnProperty注解的使用,本篇文章带大家来了解一下该注解的功能. Spring Boot中的使用 在Spring Boot的源 ...

  6. Spring Boot的启动器Starter详解

    Spring Boot的启动器Starter详解 作者:chszs,未经博主允许不得转载.经许可的转载需注明作者和博客主页:http://blog.csdn.net/chszs Spring Boot ...

  7. Spring Boot启动命令参数详解及源码分析

    使用过Spring Boot,我们都知道通过java -jar可以快速启动Spring Boot项目.同时,也可以通过在执行jar -jar时传递参数来进行配置.本文带大家系统的了解一下Spring ...

  8. Spring Boot admin 2.0 详解

    一.什么是Spring Boot Admin ? Spring Boot Admin是一个开源社区项目,用于管理和监控SpringBoot应用程序. 应用程序作为Spring Boot Admin C ...

  9. Spring Boot的SpringApplication类详解

    相信使用过Spring Boot的开发人员,都对Spring Boot的核心模块中提供的SpringApplication类不陌生.SpringApplication类的run()方法往往在Sprin ...

随机推荐

  1. 超级干货 :一文读懂数据可视化 ZT

    前言 数据可视化,是指将相对晦涩的的数据通过可视的.交互的方式进行展示,从而形象.直观地表达数据蕴含的信息和规律. 早期的数据可视化作为咨询机构.金融企业的专业工具,其应用领域较为单一,应用形态较为保 ...

  2. MySQL 性能优化--优化数据库结构之优化数据类型

    MySQL性能优化--优化数据库结构之优化数据类型   By:授客  QQ:1033553122   优化数字数据(Numeric Data) l   对于唯一ID或其它可用字符串或数字表示的值,选择 ...

  3. LearnX控件漏洞挖掘与利用

    前言 大学英语会用到一个 ActiveX 插件 LearnX ,最近从网上下了一个下来分析了一下,找到了一些漏洞并完成了 exploit . 虽然涉及的知识比较老旧,不过还是挺有意思的.这里分享一下整 ...

  4. redis介绍 (8) window 下redis的集群(cluster命令)

    前言: 前段时间我在centos上搭建过一次redis集群,那是借助ruby搭建,这次我介绍一种纯redis集群命令的方式去搭建[最后我会简单介绍ruby搭建]. redis集群搭建(三主三备): 准 ...

  5. Anaconda3 错误集合

    1. An error ocurred while starting the kernel 答:个人猜测有可能是配置文件出现问题,于是采用如下解决方法: 在终端中输入spyder --reset,重置 ...

  6. 洗礼灵魂,修炼python(26)--编程核心之“递归”

    递归 1.什么是递归: 其实前面都提过,但没有详细讲.多次调用自身就叫递归 看图,这种就叫递归 看过盗梦空间没?其实也是递归 2.递归需要满足条件: 有调用函数自身 有一个正确的返回条件来结束 在使用 ...

  7. 洗礼灵魂,修炼python(16)--列表进阶话题—>上节作业讲解+copy模块,浅拷贝,深拷贝

    上节课后作业: 1.使用列表解析输出结果:[(0,0),(0,2),(2,0),(2,2)] 方法1: 方法2: 方法3: 2.使用列表生成器打印斐波那契数列 3.使用列表解析生成列表[1x2,3x4 ...

  8. JavaScript高级特性-数组

    1. JavaScript中的数组 在C++.Java中,数组是一种高效的数据结构,随机访问性能特别好,但是局限性也特别明显,就是数组中存放的数据必须是同一类型的,而在JavaScript中,数组中的 ...

  9. oracle FLASHBACK TABLE

    闪回表 -- 开启行迁移 ALTER TABLE employees_test ENABLE ROW MOVEMENT; UPDATE employees_test SET salary = sala ...

  10. ssh登陆慢的问题

    识别主机名时卡一下,关掉DNS选项: root@ns-virtual-machine:~# grep -i dns /etc/ssh/sshd_config UseDNS no 如果还有问题,打开ve ...