-spring.config.location=文件路径

3,注入值

​ Application.properties k=v
​ Application.yml

  yml语法: 他不是标记文档 和xml不一样, 
        Server:
        Port: 8820	使用垂直对齐指定层次关系
  Xml:
        <server>
        <port>8820</port>
        </server>

实体类赋值:(yml语法)
    类名:
    属性: 值  			普通
    属性: 2020/12/23	日期date
    属性: {name:狗蛋,id:234323}	map集合
    属性: 
    - 爱好 		数组 集合
    - 爱好
    属性:
    Name: 张三		对象
    Age: 10

赋值完后需要在实体类上加注解

@ConfigurationProperties(prefix=”yml里赋值的类名”) 赋值
@Component 加入ioc容器

2020-07-17_145607

1.)@PropertySource和@ImporResource

​ @PropertySource:默认加载application.properties/application.yml文件的数据
​ 指定配置文件 @PropertySource(value={“classpath:appconfig.properties”}) 只能加载properties文件
​ 让spring boot认识spring配置文件:

​ 在主程序上加@ImporResource(locations={“class path:spring.xml”}) 不推荐

推荐使用注解方式进行配置使用

2020-07-17_154501

4,Yml里的占位符表达式

2020-07-17_163444

5,多环境切换(profile)

1.) Properties

默认会读取application.properties环境

​ 如果有多个环境:

​ 命名规范application-环境名.properties

​ 切换:在主配置文件里:spring.profiles.active=环境名

2.)yml环境切换

server:
  port: 8881
spring:                     #主环境
    profiles:
      active: dev           #指定那个环境
      
---                           #分割
server:
    port: 8882
spring:					#测试环境
    profiles: dev
    
---
server:
  port: 8883
spring:
  profiles: test

Properties的优先级高于yml

越是外边 包含的越多

3.)动态切换环境

  1. 命令行:(IDE)

    ​ --spring.profiles.active=dev 首先引用的是properties文件的环境,properties文件里没有再去yml文件找
    Idea命令行指定环境

  2. 打包DOS命令:

    ​ Java -jar 项目名.jar --spring.profiles.active=test

  3. VM和Program参数的优先级 Program比VM优先级高

    idea命令行指定VM参数

6,配置文件的加载位置

配置文件的加载位置

​ idea下对应的路径位置以及加载顺序
idea对应配置文件的加载位置

​ 优先级由高到低,高优先级会覆盖优先级低的配置 ,spring还会从这四个路径全部加载配置文件,并且产生互补配置 比如在低优先级的配置文件里配置 server.context-path=/boottest 表示项目的服务路径,这样就会和高优先级的配置文件互补配置

​ spring.config.location=路径 来改变默认的配置文件的位置 ,
​ 使用场景:当项目打包完后 需要补救的时候 可以在任何盘符下写个配置文件
​ cmd: java -jar springbootdemo-0.0.1-SNAPSHOT.jar --spring.config.location=盘符内配置文件的路径位置

7,外部配置文件加载顺序

​ Spring Boot也可以从以下位置加载配置 ,优先级从高到低,配置会形成互补

  1. 命令行参数

    ​ 打完包后 (打包只会打包main下的Java和resource下的资源)

    ​ 命令:Java -jar 打包项目 --server.prot=端口

  2. 来自Java:comp/env的JNDI属性

  3. Java系统属性(System.getProperties())

  4. 操作系统环境变量

  5. RandomValuePropertySource配置的random.*属性值

    由jar包外向jar包内找

    带profile的

  6. jar包外部的application-{profile}.properties或application.yml(带spring.profile)配置文件

  7. jar包内部的application-{profile}.properties或application.yml(带spring.profile)配置文件

    不带profile的

  8. jar包外部的application.properties或application.yml(不带spring.profile)配置文件

  9. jar包内部的application.properties或application.yml(不带spring.profile)配置文件

  10. @Configuration注解类上的@PropertySource

  11. 通过SpringApplication.setDefaultProperties值定的默认属性

8,SpringBoot自动配置 1.5.9

自动配置原理
​ spring boot启动的时候自动开启自动配置功能 @EnableAutoConfiguration
​ @EnableAutoConfiguration的作用:
​ 利用EnableAutoConfigurationImportSelector给容器导入一些组件

  • 利用EnableAutoConfigurationImportSelector给容器中导入一些组件?

  • 可以查看selectImports()方法的内容;

  • List configurations = getCandidateConfigurations(annotationMetadata, attributes);获取候选的配置

    • SpringFactoriesLoader.loadFactoryNames() 扫描所有jar包类路径下 META-INF/spring.factories 把扫描到的这些文件的内容包装成properties对象 从properties中获取到EnableAutoConfiguration.class类(类名)对应的值,然后把他们添加在容器中

      以**HttpEncodingAutoConfiguration(Http编码自动配置)**为例解释自动配置原理;

      @Configuration   //表示这是一个配置类,以前编写的配置文件一样,也可以给容器中添加组件
      @EnableConfigurationProperties(HttpEncodingProperties.class)  //启动指定类的ConfigurationProperties功能;将配置文件中对应的值和HttpEncodingProperties绑定起来;并把HttpEncodingProperties加入到ioc容器中
      
      @ConditionalOnWebApplication //Spring底层@Conditional注解(Spring注解版),根据不同的条件,如果满足指定的条件,整个配置类里面的配置就会生效;    判断当前应用是否是web应用,如果是,当前配置类生效
      
      @ConditionalOnClass(CharacterEncodingFilter.class)  //判断当前项目有没有这个类CharacterEncodingFilter;SpringMVC中进行乱码解决的过滤器;
      
      @ConditionalOnProperty(prefix = "spring.http.encoding", value = "enabled", matchIfMissing = true)  //判断配置文件中是否存在某个配置  spring.http.encoding.enabled;如果不存在,判断也是成立的
      //即使我们配置文件中不配置pring.http.encoding.enabled=true,也是默认生效的;
      public class HttpEncodingAutoConfiguration {
        
        	//他已经和SpringBoot的配置文件映射了
        	private final HttpEncodingProperties properties;
        
         //只有一个有参构造器的情况下,参数的值就会从容器中拿
        	public HttpEncodingAutoConfiguration(HttpEncodingProperties properties) {
      		this.properties = properties;
      	}
        
          @Bean   //给容器中添加一个组件,这个组件的某些值需要从properties中获取
      	@ConditionalOnMissingBean(CharacterEncodingFilter.class) //判断容器没有这个组件?
      	public CharacterEncodingFilter characterEncodingFilter() {
      		CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();
      		filter.setEncoding(this.properties.getCharset().name());
      		filter.setForceRequestEncoding(this.properties.shouldForce(Type.REQUEST));
      		filter.setForceResponseEncoding(this.properties.shouldForce(Type.RESPONSE));
      		return filter;
      	}
      

      根据当前不同的条件判断,决定这个配置类是否生效?

      一但这个配置类生效;这个配置类就会给容器中添加各种组件;这些组件的属性是从对应的properties类中获取的,这些类里面的每一个属性又是和配置文件绑定的;

      @Conditional派生注解(Spring注解版原生的@Conditional作用)

      作用:必须是@Conditional指定的条件成立,才给容器中添加组件,配置配里面的所有内容才生效;

      @Conditional扩展注解

      作用(判断是否满足当前指定条件)

      @ConditionalOnJava

      系统的java版本是否符合要求

      @ConditionalOnBean

      容器中存在指定Bean;

      @ConditionalOnMissingBean

      容器中不存在指定Bean;

      @ConditionalOnExpression

      满足SpEL表达式指定

      @ConditionalOnClass

      系统中有指定的类

      @ConditionalOnMissingClass

      系统中没有指定的类

      @ConditionalOnSingleCandidate

      容器中只有一个指定的Bean,或者这个Bean是首选Bean

      @ConditionalOnProperty

      系统中指定的属性是否有指定的值

      @ConditionalOnResource

      类路径下是否存在指定资源文件

      @ConditionalOnWebApplication

      当前是web环境

      @ConditionalOnNotWebApplication

      当前不是web环境

      @ConditionalOnJndi

      JNDI存在指定项

      自动配置类必须在一定的条件下才能生效;

三,日志框架

市面上的日志框架;

JUL、JCL、Jboss-logging、logback、log4j、log4j2、slf4j…

日志门面 (日志的抽象层)

日志实现

JCL(Jakarta Commons Logging) SLF4j(Simple Logging Facade for Java) jboss-logging

Log4j JUL(java.util.logging) Log4j2 Logback

左边选一个门面(抽象层)、右边来选一个实现;
日志门面: SLF4J;
日志实现:Logback;

spring boot选用SLF4j和logback

1,SLF4j使用

1.)如何在系统中使用SLF4j

​ 以后开发的时候,日志记录方法的调用,不应该来直接调用日志的实现类,而是调用日志抽象层里面的方法;

​ 给系统里面导入slf4j的jar和 logback的实现jar

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HelloWorld {
  public static void main(String[] args) {
    Logger logger = LoggerFactory.getLogger(HelloWorld.class);
    logger.info("Hello World");
  }
}

图示;slf4j
每一个日志的实现框架都有自己的配置文件。使用slf4j以后,配置文件还是做成日志实现框架自己本身的配置文件;

2,Spring boot日志关系

​ 依赖关系:

日志

1.)日志的级别

Logger logger = LoggerFactory.getLogger(getClass());
//日志的级别 由低到高 trace>debug>info>warn>error
//当项目上线后 不想要的日志输出可以调整级别来控制输出 比如调整为info 那么日志就会输出info及以上的日志信息
logger.trace("这是trace日志");
logger.debug("这是debug日志");
//spring boot默认日志级别是info
logger.info("这是info日志");
logger.warn("这是warn日志");
logger.error("这是error日志");

在配置文件内调整日志级别:
	logging.level.org.ph.springbootlogging=trace
	指定的是那个包下的日志级别 没有指定的就是用默认的级别 
在配置文件内指定日志的存放位置:
	logging.file.name=springboot.log		存放在项目目录			新版本
	logging.file.path=d:/springboot.log	 	存放在具体的位置

2.)指定配置

配置日志

​ 用什么日志就在相应的位置写相应的日志配置文件,那么spring boot就不再使用默认的了
更高级的配置:

​ logback.xml:直接被spring boot识别

​ logback-spring.xml: 带spring后缀的日志配置文件 ,日志框架就不再自动加载,而是由spring boot框架加载,这样配置文件就可以使用高级特性:

<!--
	日志输出格式:
		%d			:表示时间
		%thread		:表示线程名
		%-5level	:级别从左显示5个字符宽度
		%logger{50}:表示logger名字最长50个字符,否则按照句号分割
		%msg	:日志消息
		%n		:换行符
-->
<springProfile name="环境名 支持!dev">
		指定某段配置只在某个环境下有效
  <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} ----> [%thread] ----> %-5level%logger {50} - %msg%n </pattern>
</springProfile>

<springProfile name="!dev">
		指定某段配置只在某个环境下有效
  <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} ====> [%thrend] ====> %-5level%logger {50} - %msg%n </pattern>
</springProfile>

四,spring boot web开发

1,开发

​ 1.创建spring boot应用,选中需要的模块
​ 2.spring boot就默认配置好了这些场景
​ 3.编写业务代码

2,Spring Boot对与静态资源的映射规则

@ConfigurationProperties(prefix = "spring.resources",ignoreUnknownFields = false)
public class ResourceProperties {
  //可以设置和静态资源有关的配置
public void addResourceHandlers(ResourceHandlerRegistry registry) {
            if (!this.resourceProperties.isAddMappings()) {
                logger.debug("Default resource handling disabled");
            } else {
                Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
                CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
           if (!registry.hasMappingForPattern("/webjars/**")) {
                    this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"}).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
                }

                String staticPathPattern = this.mvcProperties.getStaticPathPattern();
                if (!registry.hasMappingForPattern(staticPathPattern)) {
                    this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(WebMvcAutoConfiguration.getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
                }

            }
        }

1.) 所有的 /webjars/** ,都去 classpath:/META-INF/resources/webjars/ 下找资源;

​ 静态资源都可以去:https://www.webjars.org/ 这个地方去下载依赖

 <!--引入jQuery-->
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>3.3.1</version>
        </dependency>

webjars
​ 访问路径:http://localhost:8080/webjars/jquery/3.3.1/jquery.js

2.)/** 访问当前项目的任何资源,this.staticPathPattern = “/**”; 以下是静态资源的文件夹

    private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{
      "classpath:/META-INF/resources/",
      "classpath:/resources/", 
      "classpath:/static/",
      "classpath:/public/"
    };
	"/" :代表项目的根路径

对应项目的路径位置

静态资源文件夹路径

localhost:8080/xxx 如果没有处理 就回去静态资源路径下找

3.),欢迎页的配置

​ 静态文件夹下的所有index.html都被 “/**”映射 ,满足localhost:8080 所以就会直接去静态文件夹下找index.html

3,模板引擎

​ spring boot选用Thymeleaf;

1.)引入

		<!--引入Thymeleaf-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

2.)语法

private static final Charset DEFAULT_ENCODING;
public static final String DEFAULT_PREFIX = "classpath:/templates/";
public static final String DEFAULT_SUFFIX = ".html";
private boolean checkTemplate = true;
private boolean checkTemplateLocation = true;
private String prefix = "classpath:/templates/";
private String suffix = ".html";
//规则 :只要将模板引擎放在  "classpath:/templates/" 下 Thymeleaf就能自动渲染

​ 使用:

​ 1.导入thymeleaf的命名空间

<html lag="en" xlmns:th="http://www.thymeleaf.org">
  
 <!DOCTYPE html>
<html lag="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<span th:text="${hello }">这里是不经过Controller的默认信息</span>
</body>
</html>

​ 2.使用语法:

​ Controller传过来信息 和springmvc一样即可

<span th:text="${hello }">这里是不经过Controller的默认信息</span>

3.)语法规则

​ th:text ; 改变当前元素的文本内容
​ th:任意HTML属性;来替换原生属性

……

编号

属性

描述

示例

1

th:text

计算其值表达式并将结果设置为标签的标签体

中国

,值为 null 为空时,整个标签不显示任何内容。

2

th:utext

th:text 会对结果中的特殊字符转义,th:utext 不会转义

中国

,值为 null 为空时,整个标签不显示任何内容。

3

th:attr

为标签中的任意属性设置,可以一次设置多个属性

< a href=“” th:attr=“title=‘前往百度’,href=‘http://baidu.com’”> 前往百度

4

th:*

为 html 指定的属性设值,一次设置一个

< a href=“” th:title=‘前往百度’ th:href=“‘http://baidu.com’”>前往百度< /a >

5

th:alt-title

同时为 alt 与 title 属性赋值

< a href=“#” th:alt-title=“‘th:A-B’”>th:A-B

6

th:lang-xmllang

同时为 lang 、xmllang 属性赋值

7

th:fragment

定义模板片段

8

th:insert

将被引用的模板片段插⼊到自己的标签体中

9

th:replace

将被引用的模板片段替换掉自己

10

th:include

类似于 th:insert,⽽不是插⼊⽚段,它只插⼊此⽚段的内容

11

th:remove

删除模板中的某些代码片段

12

th:each

迭代数据,如 数组、List、Map 等

13

th:if

条件为 true 时,显示模板⽚段,否则不显示

已婚1

14

th:unless

条件为 false 时,显示模板⽚段,否则不显示

已婚2

15

th:switch

与 Java 中的 switch 语句等效,有条件地显示匹配的内容

16

th:case

配合 th:switch 使用

管理员

操作员

未知用户

17

th:with

定义局部变量

18

th:inline

禁用内联表达式,内联js,内联css