date: 2019-12-27 09:00:00

updated: 2019-12-30 13:20:00

Spring Boot 学习摘要--关于配置

学习教程来自:B站 尚硅谷

1. 关于配置

1. Yaml

  1. 键值对写法:必须要有空格! k: v

  2. v 的一些写法

    • v 是对象
    friends:
    name: zhangsan
    age: 20 行内写法:
    friends: {name: zhangsan, age: 20}
    • v 是数组
    pets:
    - cat
    - dog 行内写法:
    pets: [cat,dog]

2. properties 文件

默认编码是 utf-8 编码,在获取其中的中文时可能有问题,需要修改一下设置

在 settings -> File Encodings 中勾选 “Transparent native-to-ascii conversion”

3. 获取配置中的值

  • @ConfigurationProperties

    @ConfigurationProperties(prefix = "?") 告诉 SpringBoot 将本类中的所有属性和篇日志文件中相关的配置进行绑定

    参数 prefix 指定配置文件中某一个 key 下的所有属性进行一一映射

  • @Value

    @Value 使用 $ 来获取配置中的值,或者使用 # 来实时计算

    @Value("${person.last-name}")
    private String name;
    @Value("#{11*2}")
    private int age;
xxx @ConfigurationProperties @Value
功能 批量注入配置文件中的属性 一个个指定
松散绑定 支持 不支持
SpEL 不支持 支持
JSR303数据校验 支持 不支持
复杂类型封装 eg:map 支持 不支持
  • 松散绑定:lastName / last-name / last_name 都可以识别成 lastName
  • SpEL:#{11*2} 这种方式
  • JSR303数据校验:在类上加入注解 @Validated,在变量前加入注解比如 @Email,可以自动识别是否符合邮箱格式

如果只是简单获取一下配置的值,就用@Value

4. @PropertySource 和 @ImportResource

  • @PropertySource:加载指定的配置文件,在配置类上添加

@PropertySource(value={"classpath:person.properties"})

  • @ImportResource:导入指定的配置文件,在启动类上添加

@ImportResource(locations={"classpath:xxx.xml"})

5. 配置文件占位符

#name: zhangsan
age: ${random.int} # 随机数
pet: ${name:zs}_dog # 获取前面 key 为 name 的值,如果没有,用默认值 zs 代替

6. 测试、生产多配置文件指定

  1. 使用 properties 文件,多 profiles 的形式

    application.properties: 主配置文件

    application-dev.properties: 测试配置文件

    application-prod.properties: 生产配置文件

默认启动的时候会激活主配置文件,切换配置文件时,在主配置文件中添加

spring.profiles.active=dev/prod
  1. 使用 yml 文件,多文档块的形式

appication.yml 使用 --- 三个横线可以在一个文件中添加多个文档块,相当于编写了好几个文档

server:
port: 8081
spring:
profiles:
active:dev
---
server:
port: 8082
spring:
profiles: dev ---
server:
port: 8083
spring:
profiles: prod

7. 配置文件目录

  • file:/config/ -> 项目根目录/config/
  • file:/ ->项目根目录
  • classpath:/config/ -> resources/config/
  • classpath:/ -> resources

优先级由高到低;相同配置项以高优先级的配置为主;互补配置(会全部加载)

8. 自动配置原理

Spring Boot 启动时加载主配置类,开启自动配置功能 @EnableAutoConfiguration

@EnableAutoConfiguration 的作用:

  1. 利用 AutoConfigurationImportSelector.class 给容器导入一些组件

  2. 通过 selectImports() 方法来确定哪一些配置被导入

List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes);

protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
// 扫描所有 jar 包类路径下的 META-INF/spring.factories
// 把扫描到的文件内容包装成properties对象
// 从properties中获取到EnableAutoConfiguration.class类对应的值,添加到容器中
List<String> configurations = SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader());
Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you are using a custom packaging, make sure that file is correct.");
return configurations;
}

=>

将类路径 META-INF/spring.factories 下配置的所有 EnableAutoConfiguration.class 的值加入到容器中

eg: xxxAutoConfiguration.class 每一个这样的类都是容器中的一个组件,加入到容器后,再用他们来做自动配置

能配置的属性都来源于 xxxAutoConfiguration.class 类对应的 xxxProperties.class

xxxProperties.class 类前会有很多注解,比如 @ConditionalOnWebApplication 用来判断是否是一个web应用,如果是返回true,下面的内容才生效,等等注解。即自动配置类是需要在一定条件下才能生效

可以通过在 application.properties 文件中添加 debug=true 来打印出自动配置报告,看到哪一类自动配置类启动了哪一些没启动

总结:

  1. xxxAutoConfiguration:自动配置类,给容器添加组件
  2. xxxProperties:封装配置文件中相关属性

Spring Boot 学习摘要--关于配置的更多相关文章

  1. Spring Boot 学习摘要--关于日志框架

    date: 2020-01-05 16:20:00 updated: 2020-01-08 15:50:00 Spring Boot 学习摘要--关于日志框架 学习教程来自:B站 尚硅谷 1. 关于日 ...

  2. spring boot 学习(十)SpringBoot配置发送Email

    SpringBoot配置发送Email 引入依赖 在 pom.xml 文件中引入邮件配置: <dependency> <groupId>org.springframework. ...

  3. Spring Boot学习一之配置类及自动配置

    一.配置类 1. 导入其他配置类 你不需要将所有的 @Configuration 放进一个单独的类, @Import 注解可以用来导入其他配置类.另外,你也可以使用 @ComponentScan 注解 ...

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

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

  5. Spring Boot学习大全(入门)

    Spring Boot学习(入门) 1.了解Spring boot Spring boot的官网(https://spring.io),我们需要的一些jar包,配置文件都可以在下载.添置书签后,我自己 ...

  6. Spring Boot学习记录(二)--thymeleaf模板 - CSDN博客

    ==他的博客应该不错,没有细看 Spring Boot学习记录(二)--thymeleaf模板 - CSDN博客 http://blog.csdn.net/u012706811/article/det ...

  7. Spring boot学习1 构建微服务:Spring boot 入门篇

    Spring boot学习1 构建微服务:Spring boot 入门篇 Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框 ...

  8. Spring Boot学习笔记2——基本使用之最佳实践[z]

    前言 在上一篇文章Spring Boot 学习笔记1——初体验之3分钟启动你的Web应用已经对Spring Boot的基本体系与基本使用进行了学习,本文主要目的是更加进一步的来说明对于Spring B ...

  9. spring boot学习笔记2

    开场知识: spring 容器注入bean,时容器初始化的一些接口以及接口调用的时间先后顺序: 1)BeanFactoryPostProcessor 容器初始化的回调方法 * BeanFactoryP ...

随机推荐

  1. 趣图:我说自己菜 vs 大佬说自己菜

      扩展阅读 一大波趣图:CSS的力量 趣图:嫁人就嫁程序员,大妈都懂的! 趣图:向客户介绍的产品VS实际开发的产品 如何准备校招技术面试+一只小菜鸟的面试之路 向Spring大佬低头--大量源码流出 ...

  2. MySQL-Atlas--读写分离架构

    一.Atlas简介 Atlas是由 Qihoo 360公司Web平台部基础架构团队开发维护的一个基于MySQL协议的数据中间层项目.它在MySQL官方推出的MySQL-Proxy 0.8.2版本的基础 ...

  3. Python-类属性查询协议-__getattr__ __getattribute__

    __getattr__ 查找不到类属性的时候调用 class BeiMenChuiXue: def __init__(self, name): self.name = name def __getat ...

  4. 2020HC大会上,这群人在讨论云原生…

    启程 一年一度的华为全联接大会又开启了,伴随着一封来自华为全联接大会的邀请函,我来到了2020华为全联接大会的现场. 理解 今年,华为全联接大会的主题是:共 创 行 业 新 价 值!(NEW VALU ...

  5. Leetcode-栈&队列

    20. 有效的括号 https://leetcode-cn.com/problems/valid-parentheses/ 给定一个只包括 '(',')','{','}','[',']' 的字符串,判 ...

  6. Docker操作命令——查看、停止、删除容器

    列出所有容器 ID docker ps -aq 停止所有容器 docker stop $(docker ps -aq) 停止单个容器 docker stop 要停止的容器名 删除所有容器 docker ...

  7. 手写“SpringBoot”近况:IoC模块已经完成

    jsoncat:https://github.com/Snailclimb/jsoncat (About 仿 Spring Boot 但不同于 Spring Boot 的一个轻量级的 HTTP 框架) ...

  8. 星涛:采用java递归复制文件夹

    package com.botao; import java.io.*; /** * @author cbt28 */ public class FileUtil { public static St ...

  9. 初学者的Android移植:在Debian上建立一个稳定的构建环境

    介绍 通过在chrooted环境中设置开发环境,避免依赖冲突和沙箱您的Android开发从您的Debian GNU/Linux系统.这是为通配符类别准备的,因为从源代码构建Android似乎没有在其他 ...

  10. ubuntu20 使用命令安装 rabbitmq

    安装 rabbitmq sudo apt-get install erlang-nox -y sudo apt-get update sudo apt-get install rabbitmq-ser ...