Spring Boot 可以通过properties文件,YAML文件,环境变量和命令行参数进行配置。属性值可以通过,@Value注解,Environment或者ConfigurationProperties注入到应用中。 配置的优先级如下:

  1. 如果使用了devtools,则以home目录下的~/.spring-boot-devtools.properties为主
  2. @TestPropertySource注解的测试
  3. @SpringBootTest#properties注解的测试
  4. 命令行参数
  5. SPRING_APPLICATION_JSON提供的属性(JSON格式,从环境变量或者系统属性中获取)
  6. ServletConfig配置的属性
  7. ServletContext配置的属性
  8. JNDI配置的属性,(java:comp/env)
  9. Java 系统属性,System.getProperties()
  10. 系统环境变量
  11. RandomValuePropertySource进针对于random.*
  12. jar包外部指定profile文件,例如application-{profile}.properties(YAML 同)
  13. jar包内部的指定profile文件
  14. 应用外部的application.properties
  15. 应用内部的application.properties
  16. @PropertySource注解
  17. 默认属性(SpringApplication.setDefaultProperties()) 例如:
import org.springframework.stereotype.*
import org.springframework.beans.factory.annotation.* @Component
public class MyBean { @Value("${name}")
private String name; // ... }

application.properties提供了name的默认值,当运行程序的时候可以通过提供命令行的值覆盖其默认值,java -jar app.jar --name="spring"

配置随机值

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会将命令行参数转换为property并添加到Environment中。正如前面提到的,命令行参数会覆盖其他的配置。 如果不希望命令行参数添加到Environment中可以通过调用SpringApplication.setAddCommandLineProperties(fals)设置。

应用配置文件

SpringApplication加载application.properties文件,将其变量添加到Environment中,查找位置: 1. 当前目录的/config目录 2. 当前目录 3. classpath下的config子目录 4. classpath目录 如果不想使用application.properties文件可以使用spring.config.name指定配置名字,同样可以通过spring.config.location指定配置文件的位置

java -jar myproject.jar --spring.config.name=myproject
java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties

如果spring.config.location使用的是目录,那么其应该以/结尾,运行的时候会将spring.confing.name的名字追加到后来查找配置文件。

指定配置文件

除了application.properties文件外,同样可以以application-{profile}.properties的形式命名指定配置文件。Environment有一个默认的配置,(default),即如果没有激活其他配置文件,默认使用application-default.properties。如果提供了多个指定配置文件,则选择最新的配置文件。

配置文件的占位符

application.properties中的定义的值可以在后续的配置中使用,例如

app.name=MyApp
app.description=${app.name} is a Spring Boot application
使用YAML配置文件

当添加了SnakeYAML时,SpringApplication即可支持YAML配置,添加spring-boot-starter 自动会添加对SnakeYAML的依赖。

加载YAML

SpringApplication有两种加载YAML配置文件的方式,1.使用YamlPropertiesFactoryBean将YAML加载为Properties,2. 使用YamlMapFactoryBean将YAML加载为map。 以下YAML配置文件:

environments:
dev:
url: http://dev.example.com
name: Developer Setup
prod:
url: http://another.example.com
name: My Cool App

上面的配置文件等同的properties配置

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列表默认会添加序号(index)例如:

my:
servers:
- dev.example.com
- another.example.com

等同的properties配置为

my.servers[0]=dev.example.com
my.servers[1]=another.example.com

可以通过@ConfigurationProperties注解将属性绑定到变量中,例如:

@ConfigurationProperties(prefix="my")
public class Config { private List<String> servers = new ArrayList<String>(); public List<String> getServers() {
return this.servers;
}
}
多个YAML配置文件

可以在单个文件中使用spring.profiles作为key指定多个YAML配置文件。例如:

server:
address: 192.168.1.100
---
spring:
profiles: development
server:
address: 127.0.0.1
---
spring:
profiles: production
server:
address: 192.168.1.120

按照上述文件表示,如果development配置激活了,则server.address设置为127.0.0.1。同样的,如果production配置激活则server.address配置为192.168.1.120。如果development和production都没有启用,则使用默认即server.address设置为192.168.1.100 如果没有指定激活哪个配置,那么默认使用default的配置,例如以下示例,spring.security.user.password只有在都不指定激活配置的时候才会使用

server:
port: 8000
---
spring:
profiles: default
security:
user:
password: weak

下面的例子密码都会被设置,因为他不属于任何一个配置:

server:
port: 8000
spring:
security:
user:
password: weak
使用@ConfigurationProperties注入值

从多个properties注入值的时候使用@Value()非常的麻烦,Spring Boot可以使用@ConfigurationProperties进行简化配置,例如:

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("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.enable=false
acme.remote-address=192.168.1.1
acme.security.username=username
acme.security.password=password
acme.security.roles=roles1,roles2

需要在@Configuration的配置中起用

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

当然如果AcmeProperties类是一个bean则无需配置指定@EnableConfigurationProperties(AcmeProperties.class)例如:

@Component
@ConfigurationProperties(prefix="acme")
public class AcmeProperties { // ... see the preceding example }

等同的YAML配置文件

acme:
remote-address: 192.168.1.1
security:
username: admin
roles:
- USER
- ADMIN
松绑定规则

通过@ConfigurationProperties绑定变量非常的灵活,例如:

@ConfigurationProperties(prefix="acme.my-project.person")
public class OwnerProperties { private String firstName; public String getFirstName() {
return this.firstName;
} public void setFirstName(String firstName) {
this.firstName = firstName;
} }

对于下列的方式都可以成功绑定

  • acme.my-porject.person.first-name
  • acme.my-project.person.first_name
  • acme.my-project.person.firstName
  • ACME_MYPROJECT_PERSON_FIRSTNAME
@ConfigurationProperties 校验

@ConfigurationProperties 支持JSR-303 javax.validation注解进行校验,例如

@ConfigurationProperties(prefix="acme")
@Validated
public class AcmeProperties { @NotNull
private InetAddress remoteAddress; // ... getters and setters }
@ConfigurationProperties和@Value的区别
功能 @configurationProperties @Value
松绑定规则 Y N
元数据支持 Y N
SPEL N Y
Profiles

Spring Profile可以将应用的配置分成多部分,只有在指定的环境下生效。任何@component或者@Configutaion都可以使用@Profile限制其加载,例如

@Configuration
@Profile("production")
public class ProductionConfiguration { // ... }

可以使用spring.profiles.activeEnvironment变量设置激活哪个profile。例如在application.properties中设置

spring.profiles.active=dev,hsqldb

或者使用命令行

java -jar app.jar --spring.profiles.active=dev,hsqldb
原文连接:https://www.codemore.top/cates/Backend/post/2018-05-20/spring-boot-configuration/

Spring Boot 2.0 教程 - 配置详解的更多相关文章

  1. Spring Boot 2.0 教程 | 配置 Undertow 容器

    欢迎关注个人微信公众号: 小哈学Java, 文末分享阿里 P8 资深架构师吐血总结的 <Java 核心知识整理&面试.pdf>资源链接!! 文章首发于个人网站 https://ww ...

  2. spring boot slf4j日记记录配置详解

    https://blog.csdn.net/liuweixiao520/article/details/78900779

  3. Spring Boot的每个模块包详解

    Spring Boot的每个模块包详解,具体如下: 1.spring-boot-starter 这是Spring Boot的核心启动器,包含了自动配置.日志和YAML. 2.spring-boot-s ...

  4. Spring Boot源码中模块详解

    Spring Boot源码中模块详解 一.源码 spring boot2.1版本源码地址:https://github.com/spring-projects/spring-boot/tree/2.1 ...

  5. spring boot 配置文件properties和YAML详解

    spring boot 配置文件properties和YAML详解 properties中配置信息并获取值. 1:在application.properties配置文件中添加: 根据提示创建直接创建. ...

  6. Apache2.2+Tomcat7.0整合配置详解

    一.简单介绍 Apache.Tomcat Apache HTTP Server(简称 Apache),是 Apache 软件基金协会的一个开放源码的网页服务器,可以在 Windows.Unix.Lin ...

  7. 【Spring】——声明式事务配置详解

    项目中用到了spring的事务: @Transactional(rollbackFor = Exception.class, transactionManager = "zebraTrans ...

  8. Spring Boot 2.0 教程 | AOP 切面统一打印请求日志

    欢迎关注微信公众号: 小哈学Java 文章首发于个人网站 https://www.exception.site/springboot/spring-boot-aop-web-request 本节中,您 ...

  9. Spring Boot 2.0 教程 - 深入SpringAplication

    原文连接:https://www.codemore.top/cates/Backend/post/2018-05-20/spring-boot-SpringApplication 可以通过Spring ...

随机推荐

  1. Android特效专辑(十一)——仿水波纹流量球进度条控制器,实现高端大气的主流特效

    Android特效专辑(十一)--仿水波纹流球进度条控制器,实现高端大气的主流特效 今天看到一个效果挺不错的,就模仿了下来,加上了一些自己想要的效果,感觉还不错的样子,所以就分享出来了,话不多说,上图 ...

  2. java--银行业务调度系统

    转载请申明出处:http://blog.csdn.net/xmxkf   1. 银行调度业务系统的题目来源与需求阐述 银行业务调度系统: 模拟实现银行业务调度系统逻辑,具体需求如下: 1.银行内有6个 ...

  3. vimgrep 搜索总结

    vimgrep /匹配模式/[g][j] 要搜索的文件/范围  g:表示是否把每一行的多个匹配结果都加入 j:表示是否搜索完后定位到第一个匹配位置 vimgrep /pattern/ %       ...

  4. LeetCode(52)-Remove Linked List Elements

    题目: Remove all elements from a linked list of integers that have value val. Example Given: 1 --> ...

  5. Oracle100w数据大表割接

    [现网问题] 最近在给咪咕做视频后台管理,移动那边希望页面上,码流字段可以支持1位小数,如8.0.自己查看数据库,发现码流字段是Number整型,也就是要换类型,打算直接换成varchar2.因为自己 ...

  6. Modelsim中使用TCL脚本编写do文件实现自动化仿真

    通常我们使用Modelsim进行仿真,是通过图形界面点点点来进行操作,殊不知Modelsim完美支持TCL脚本语言及批处理命令do文件.简单来说就是从你修改完代码后到你重新编译把需要的信号拉出来查看, ...

  7. Collections模块下的Counter

    class Counter(dict) 这个类是dict的子类,对哈希类型的项进行计数,元素被存储为字典的键,他们的计数将作为字典的键值. 主要介绍两个方法: 1.初始化方法:__init__(*ar ...

  8. linux下安装apc

    wget htdtp://pecl.php.net/get/APC tar zxvf APC-3.1.3p.tgz cd APC-3.1.3p /usr/local/php/bin/phpize ./ ...

  9. php进阶篇

    字符串调用: $name = 'eco'; echo $name; //eco //双引号会解析变量 echo "$name"; //eco //单引号不会解析变量 echo '$ ...

  10. Cython入门Demo(Linux)

    众所周知,Python语言是非常简单易用的,但是python程序在运行速度上还是有一些缺陷.于是,Cython就应运而生了,Cython作为Python的C扩展,保留了Python的语法特点,集成C语 ...