SpringBoot入门(五)——自定义配置
本文来自网易云社区
大部分比萨店也提供某种形式的自动配置。你可以点荤比萨、素比萨、香辣意大利比萨,或者是自动配置比萨中的极品——至尊比萨。在下单时,你并没有指定具体的辅料,你所点的比萨种类决定了所用的辅料。但如果你想要至尊比萨上的全部辅料,还想要加墨西哥胡椒,又不想放蘑菇该怎么办?你偏爱辣食又不喜欢吃菌类,自动配置不适合你的口味,你就只能自己配置比萨了吗?当然不是,大部分比萨店会让你以菜单上已有的选项为基础进行定制。
外化属性
属性源
为了使应用能适应不同的环境,SpringBoot支持外化配置。可以使用.properties文件、YAML文件、环境变量、命令行参数等方式。
SpringBoot能从多种属性源获得属性,包括以下几处:
命令行参数
JVM系统属性
操作系统环境变量
随机生成的带random.*前缀的属性(在设置其他属性时,可以引用它们,比如${random.long})
应用程序以外的application.properties或者application.yml文件
打包在应用程序内的application.properites或者application.yml文件
通过@propertySource标注的属性源
默认属性
优先级由高到低,即在上面的列表中“命令行参数”的优先级最高,会覆盖下面其他属性源的相同配置。
这里只挑选了部分比较常见的属性源,详细信息可以参考官网教程:24. Externalized Configuration
默认情况下SpringApplication将任何可选的命令行参数(以'--'开头,比如,--server.port=9000)转化为property,并将其添加到Spring Environment中。如上所述,命令行属性总是优先于其他属性源。
如果不想用这个特性可以用SpringApplication.setAddCommandLineProperties(false)来禁用。
YAML
SpringBoot支持YAML格式的配置文件文件后缀为yml,是一种更易读写的通用的数据串行化格式。
在SpringBoot中.yml效果相当于.properties,通常情况下二者是可以互相替换的,比如下面2种配置文件在SpringBoot中是等效的:
application.properties
server.port=8020
server.address=127.0.0.1
application.yml
server: port: 8020 address: 127.0.0.1
.yml文件在配置数据的时候具有面向对象的特性,更易阅读。
虽然.yml配置和.properties基本等效,但也有略微区别,.yml配置不能用@propertySource注解加载。
Application属性文件
SpringBoot会从以下位置加载.properties或.yml配置文件:
当前目录下的/config目录
当前目录
classpath下的/config目录
classpath的根目录
优先级也是从高到低,高优先级的配置文件会覆盖低优先级的配置。
使用.properties或.yml配置文件可以对SpringBoot的自动配置进行覆盖,比如在默认的情况下http端口为8080,我们可以像上面的例子那样在修改为8020。
SpringBoot提供了上百个这样可以覆盖的配置,具体可以查阅官网或者查看autoconfiguration包的的META-INF/spring-configuration-metadata.json和META-INF/additional-spring-configuration-metadata.json文件(这2个文件用来给IDE做输入提示用,有一些简单的描述)。
类型安全的配置属性
有时候使用@Value("#{property}")注解注入配置会比较笨重,SpringBoot提供一个类型安全的方案,用强类型的Bean对象来替代属性。
@ConfigurationProperties用法如下
@ConfigurationProperties(prefix = "acme")public class AcmeProperties { private boolean enabled; private final Security security = new Security(); // 省略getter、setter
public static class Security { private String username; private String password; private List<String> roles = new ArrayList<>(Collections.singleton("USER")); // 省略getter、setter
}
}
@ConfigurationProperties的参数prefix表示前缀,AcmeProperties里的每个属性的名称便是具体的配置名。比如成员变量enabled绑定属性acme.enabled。
上面这个例子表示AcmeProperties对象分别绑定下列属性:
acme.ebalbe:布尔类型
acme.security.username:String类型
acme.security.pasword:String类型
acme.security.roles:类型是一个String集合
绑定配置之后还需要注册Spring上下文中,有3种方式:
在java配置类中用@EnableConfigurationProperties注解激活
@Configuration@EnableConfigurationProperties(AcmeProperties.class)public class MyConfiguration {
}
直接在AcmeProperties加@Component注解
@Component@ConfigurationProperties(prefix="acme")public class AcmeProperties { // ... see the preceding example}
在配置类中与@Bean注解组合
@Beanpublic AnotherComponent anotherComponent() {
...
}
注册之后,可以在任意地方使用@Autowire注解注入使用。
松散的绑定(Relaxed binding)
Spring Boot使用一些宽松的规则用于绑定Environment属性到@ConfigurationProperties beans,所以Environment属性名和bean属性名不需要精确匹配。常见的有虚线匹配大写(比如,context-path绑定到contextPath)和将环境属性转为大写字母(比如,PORT绑定port)。
比如:
@ConfigurationProperties(prefix="acme.my-project.person")public class OwnerProperties { private String firstName; // 省略getter、setter}
可以绑定到:
| Property | Note |
|---|---|
| acme.my-project.person.firstName | 标准的驼峰式命名 |
acme.my-project.person.first-name |
虚线表示,适用于.properties和.yml |
acme.my-project.person.first_name |
下划线表示,适用于.properties和.yml |
ACME_MYPROJECT_PERSON_FIRSTNAME |
大写形式,适用于环境变量 |
@ConfigurationProperties vs @Value
| Feature | @ConfigurationProperties |
@Value |
|---|---|---|
| Relaxed binding | Yes | No |
| Meta-data support | Yes | No |
SpEL evaluation |
No | Yes |
其他
查看当前生效的配置
SpringBoot默认提供了大量的自动配置,我们可以通过启动时添加--debug参数来查看当前的配置信息。
激活的配置如下:
Positive matches:----------------- CodecsAutoConfiguration matched:
- @ConditionalOnClass found required class 'org.springframework.http.codec.CodecConfigurer'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition) CodecsAutoConfiguration.JacksonCodecConfiguration matched:
- @ConditionalOnClass found required class 'com.fasterxml.jackson.databind.ObjectMapper'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)...
未激活的配置如下:
Negative matches:-----------------
ActiveMQAutoConfiguration:
Did not match:
- @ConditionalOnClass did not find required classes 'javax.jms.ConnectionFactory', 'org.apache.activemq.ActiveMQConnectionFactory' (OnClassCondition)
AopAutoConfiguration:
Did not match:
- @ConditionalOnClass did not find required classes 'org.aspectj.lang.annotation.Aspect', 'org.aspectj.lang.reflect.Advice', 'org.aspectj.weaver.AnnotatedElement' (OnClassCondition)
...
可以清楚的看到每个配置的条件,未激活的配置可以从这里直观的看到原因。
debug可以用-Ddebug或--debug来启用,也可以在.properties或.yml文件中配置debug的值为true。
去除指定的自动配置
用@EnableAutoConfiguration注解的exclude参数去除指定的自动配置:
import org.springframework.boot.autoconfigure.*;import org.springframework.boot.autoconfigure.jdbc.*;import org.springframework.context.annotation.*;@Configuration@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})public class MyConfiguration {
}
小结
本节介绍了SpringBoot自定义配置的几种方式。通过属性外化,我们可以灵活选择不同的属性元来应对不同的场景。利用YAML可以让配置文件结构化更易于阅读,特别是有多层结构的属性。@ConfigurationProperties提供类型安全的属性使用方式,使用起来更加直观。组合使用YAML和@ConfigurationProperties相信能让项目的配置变得更加清晰。
SpringBoot不仅仅是帮助我们快速搭建一个可用的项目,在使用便利性上也提供了更多的姿势。
网易云新用户大礼包:https://www.163yun.com/gift
本文来自网易实践者社区,经作者金港生授权发布。
SpringBoot入门(五)——自定义配置的更多相关文章
- springboot 入门八-自定义配置信息(编码、拦截器、静态资源等)
若想实际自定义相关配置,只需要继承WebMvcConfigurerAdapter.WebMvcConfigurerAdapter定义些空方法用来重写项目需要用到的WebMvcConfigure实现.具 ...
- ASP.NET 5 入门 (2) – 自定义配置
ASP.NET 5 入门 (2) – 自定义配置 ASP.NET 5 理解和入门 建立和开发ASP.NET 5 项目 初步理解ASP.NET5的配置 正如我的第一篇文章ASP.NET 5 (vNext ...
- SpringBoot入门之简单配置
今天下载了<JavaEE开发的颠覆者SpringBoot实战>这本书,发现Spring还有好多遗漏的部分,算是又恶补了一下,今天主要是学习下SpringBoot的配置. 一.基本配置 1. ...
- spring-boot 速成(4) 自定义配置
spring-boot 提供了很多默认的配置项,但是开发过程中,总会有一些业务自己的配置项,下面示例了,如何添加一个自定义的配置: 一.写一个自定义配置的类 package com.example.c ...
- SpringBoot使用logback自定义配置时遇到的坑 --- 在 /tmp目录下自动生成spring.log文件
问题描述 SpringBoot项目使用logback自定义配置后,会在/tmp/ 目录下生成 spring.log的文件(如下图所示). 解决方案 通过各种资料的搜索,最终发现问题的所在(logbac ...
- 01.springboot入门--启用自动配置注解EnableAutoConfiguration
springboot入门 <parent> <groupId>org.springframework.boot</groupId> <artifactId&g ...
- springboot 入门二- 读取配置信息一
在上篇入门中简单介绍下springboot启动使用了大量的默认配置,在实际开发过程中,经常需要启动多个服务,那端口如何手动修改呢? 此篇就是简单介绍相关的配置文件信息. Spring Boot允许外部 ...
- springboot 入门三- 读取配置信息二(读取属性文件方式)
在上篇文章中简单介绍自带读取方式.springboot提供多种方式来读取 一.@ConfigurationProperties(value="my") 支持更灵活的绑定及元数据的支 ...
- springboot 入门五-日志一
springboot内部采用commons logging作为日志纪录,但也保留了第三方的日志框架接入的实现,例如Java Util Logging,Log4J2还有Logback.如果你要实现一种日 ...
- SpringBoot入门教程(八)配置logback日志
Logback是由log4j创始人设计的又一个开源日志组件.logback当前分成三个模块:logback-core,logback- classic和logback-access.logback-c ...
随机推荐
- 模式:模版、样式;属于分类、识别的范围;分类、归类的标准-How are patterns obtained?
模式及套路 模式:模版.样式:属于分类.识别的范围. How are patterns obtained? Through : re-use, classification and finally a ...
- c#根据当前时间获取本周,本月,本年度等时间段和DateTime日期格式化
DateTime dt = DateTime.Now; //当前时间 DateTime startWeek = dt.AddDays( - Convert.ToInt32(dt.DayOfWeek.T ...
- HDU 6470 Count 【矩阵快速幂】(广东工业大学第十四届程序设计竞赛 )
题目传送门:http://acm.hdu.edu.cn/showproblem.php?pid=6470 Count Time Limit: 6000/3000 MS (Java/Others) ...
- Exhaustive Search
Write a program which reads a sequence A of n elements and an integer M, and outputs "yes" ...
- Mabatis入门案例
log4j.properties # Global logging configuration #\u5728\u5f00\u53d1\u9636\u6bb5\uff0c\u8bbe\u7f6e\u4 ...
- redis-desktop-manager 安装——redis的可视化工具
一.redis-desktop-manager介绍 Redis可视化工具之一,RedisDesktopManager是开源的,托管在github上:https://github.com/uglide/ ...
- Number & Math
Java Number & Math 类 一般地,当需要使用数字的时候,我们通常使用内置数据类型,如:byte.int.long.double 等. 实例 int a = 5000; floa ...
- 控制DIV中的文字绝对居中
水平居中:<div align="center">Content</div> 垂直居中:<div style="line ...
- CSS3-transition常用属性及示例
transition参数 语法 transition: property duration timing-function delay transition属性是个复合属性,她包括以下几个子属性: t ...
- uiwebview与objective-c
利用oc调用js很简单, 系统直接提供了方法stringByEvaluatingJavaScriptFromString [webView stringByEvaluatingJavaScriptFr ...