Spring Boot-开发基础3

@ConditionalOnJava

在这里插入图片描述

怎么知道哪些自动配置类生效
在.properties文件中编写

debug=true

控制台打印自动配置报告,Positive matches:自动配置类启用,Negative matches为没有启用

Spring Boot与日志

日志框架、日志配置
统一的接口层:日志门面(日志的抽象层)

JUL(java.util.logging)、JCL(Apache/Jakarta Commons Logging)、Jboss-logging、logback、log4j、log4j2、slf4j(Simple Logging Facade for Java)
日志
Spring boot使用JCL,spring-boot-starter-logging采用slf4j+logback的形式
日志门面:SLF4j
日志实现:Logback

LogFactory = new SLF4JLogFactory()

  • SpringBoot底层也是使用slf4j+logback的方式进行日志记录
  • SpringBoot也把其他的日志都替换成slf4j
  • 中间替换包,如jcl-over-slf4j
  • 如果引入其他框架,需要移除框架的默认日志依赖
    spring框架用的是commons-logging
 <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <exclusions>
                <exclusion>
                 <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</groupId>
                </exclusion>
            </exclusions>
        </dependency>

== springboot能自动适配所有日志,而且底层使用slf4j+logback的方式记录日志,引入其他框架时,排除依赖的日志框架==

日志的使用

  1. 默认配置
    日志配置
 日志输出格式:
    		%d表示日期时间,
    		%thread表示线程名,
    		%-5level:级别从左显示5个字符宽度
    		%logger{50} 表示logger名字最长50个字符,否则按照句点分割。 
    		%msg:日志消息,
    		%n是换行符
        %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
# 配置日志级别
logging.level.com.qtu.zp = trace

Springboot(slf4j+logback)、Spring(common-logging)、Hibernate(jboos-logging)、Mybatis
统一日志记录,即使是别的框架统一使用slf4j进行输出。

##### 将系统的所有日志统一到slf4j
1. ==将系统中其他日志框架先排除出去==
2. ==用中间包来替换原先的日志框架==
3. ==导入slf4j其他的实现==
[slf4j的官方文档](https://www.slf4j.org/docs.html)

**使用**
不应该直接调用日志的实现类,调用日志抽象层里面的方法
给系统导入slf4j和logback的实现jar包 

### 输出到指定目录
#在当前磁盘的根路径下创建spring/log文件夹
#logging.path= /spring/log
#输出到指定的文件中
#不指定路径,默认在当前项目下创建,
#可以指定完整路径路径
#logging.file=G:/zp.log
#日志在控制台输出的格式
logging.pattern.console=
#指定文件中日志输出格式
logging.pattern.file=
 public void contextLoads() {
//        log:日志, logger:记录器
//        日志级别:由低到高,可以调整输出砈日志级别
        logger.trace("这是trace日志");
        logger.debug("this is debug log");
//        默认使用info级别
//        设置日志级别:在配置文件中编写logging.level.com.qtu.zp = trace,root级别
        logger.info("this is info");
        logger.warn("this is warning logger");
        logger.error(("this is error logger"));
    }
指定配置文件

给类路径放上每个日志框架自己的配置文件,SpringBoot就不使用默认配置

对应的配置文件

logback.xml:会被框架自动识别
logback-spring.xml:日志框架就不直接加载日志的配置项,由SpringBoot解析日志配置,可以使用SpringBoot的高级Profile功能

Web开发

使用SpringBoot
1. 创建SpringBoot应用,选中需要的模块
2. 编写配置文件
3. 编写业务代码

自动配置原理
xxxAutoConfiguration:自动配置类
xxxProperties:封装配置文件内容
yml/properties文件中能配置的值来源于[属性配置类]

Bootstrap example

SpringBoot对静态资源的映射规则

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

​ webjars:以jar包的方式引入静态资源;
webjars官方网站

  • 设置和静态资源相关的参数,缓存时间等
    ResourceProperties
  • 添加资源映射
  • "/" 访问当前项目的任何资源,都去(静态资源的文件夹)找映射**
"classpath:/META-INF/resources/", 
"classpath:/resources/",
"classpath:/static/", 
"classpath:/public/" 
"/":当前项目的根路径
  • 欢迎页; 静态资源文件夹下的所有index.html页面;被"/**"映射
  • 所有的 **/favicon.ico 都是在静态资源文件下找;

模板引擎

JSP、Velocity、FreeMarker、Thymeleaf

Thymeleaf

  1. 引入模板引擎
  2. 切换thymeleaf版本
<properties>
		<thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
		<!-- 布局功能的支持程序  thymeleaf3主程序  layout2以上版本 -->
		<!-- thymeleaf2   layout1-->
		<thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
  </properties>
  1. 使用&语法
    放template文件夹下
    只要我们把HTML页面放在classpath:/templates/,thymeleaf就能自动渲染;

1、导入thymeleaf的名称空间

<html lang="en" xmlns:th="http://www.thymeleaf.org">

2、使用thymeleaf语法;

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>成功!</h1>
    <!--th:text 将div里面的文本内容设置为指定值 -->
    <div th:text="${hello}">这是显示欢迎信息</div>
</body>
</html>

3、语法规则

1)、th:text;改变当前元素里面的文本内容;

​ th:任意html属性;来替换原生属性的值
解析的优先级

优先级

  • 五种表达式
Simple expressions:(表达式语法)
    Variable Expressions: ${...}:获取变量值;OGNL;
    		1)、获取对象的属性、调用方法
    		2)、使用内置的基本对象:
    			#ctx : the context object.
    			#vars: the context variables.
                #locale : the context locale.
                #request : (only in Web Contexts) the HttpServletRequest object.
                #response : (only in Web Contexts) the HttpServletResponse object.
                #session : (only in Web Contexts) the HttpSession object.
                #servletContext : (only in Web Contexts) the ServletContext object.
                
                ${session.foo}
            3)、内置的一些工具对象:
#execInfo : information about the template being processed.
#messages : methods for obtaining externalized messages inside variables expressions, in the same way as they would be obtained using #{…} syntax.
#uris : methods for escaping parts of URLs/URIs
#conversions : methods for executing the configured conversion service (if any).
#dates : methods for java.util.Date objects: formatting, component extraction, etc.
#calendars : analogous to #dates , but for java.util.Calendar objects.
#numbers : methods for formatting numeric objects.
#strings : methods for String objects: contains, startsWith, prepending/appending, etc.
#objects : methods for objects in general.
#bools : methods for boolean evaluation.
#arrays : methods for arrays.
#lists : methods for lists.
#sets : methods for sets.
#maps : methods for maps.
#aggregates : methods for creating aggregates on arrays or collections.
#ids : methods for dealing with id attributes that might be repeated (for example, as a result of an iteration).

    Selection Variable Expressions: *{...}:选择表达式:和${}在功能上是一样;
    	补充:配合 th:object="${session.user}:
   <div th:object="${session.user}">
    <p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>
    <p>Surname: <span th:text="*{lastName}">Pepper</span>.</p>
    <p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>
    </div>
    
    Message Expressions: #{...}:获取国际化内容
    Link URL Expressions: @{...}:定义URL;
    		@{/order/process(execId=${execId},execType='FAST')}
    Fragment Expressions: ~{...}:片段引用表达式
    		<div th:insert="~{commons :: main}">...</div>
    	----------------------------------------------------------	
Literals(字面量)
      Text literals: 'one text' , 'Another one!' ,…
      Number literals: 0 , 34 , 3.0 , 12.3 ,…
      Boolean literals: true , false
      Null literal: null
      Literal tokens: one , sometext , main ,…
Text operations:(文本操作)
    String concatenation: +
    Literal substitutions: |The name is ${name}|
Arithmetic operations:(数学运算)
    Binary operators: + , - , * , / , %
    Minus sign (unary operator): -
Boolean operations:(布尔运算)
    Binary operators: and , or
    Boolean negation (unary operator): ! , not
Comparisons and equality:(比较运算)
    Comparators: > , < , >= , <= ( gt , lt , ge , le )
    Equality operators: == , != ( eq , ne )
Conditional operators:条件运算(三元运算符)
    If-then: (if) ? (then)
    If-then-else: (if) ? (then) : (else)
    Default: (value) ?: (defaultvalue)
Special tokens:
    No-Operation: _ 

[[]]等于th:text,转义会变成普通字符串
[()]等于th:utext,不转义的话会变成html代码

SpringMVC自动配置

1. Spring MVC auto-configuration

自动配置了ViewResolver(视图解析器:根据方法的返回值得到视图对象(View),视图对象决定如何渲染(转发?重定向?))

  • ContentNegotiatingViewResolver:组合所有的视图解析器的;

  • 如何定制:我们可以自己给容器中添加一个视图解析器;自动的将其组合进来;

  • 静态资源文件夹路径,webjars

  • 静态首页访问

  • favicon.ico

  • 自动注册了 of Converter, GenericConverter, Formatter beans.

    • Converter:转换器; public String hello(User user):类型转换使用Converter
    • Formatter 格式化器; 2017.12.17===Date;
    • 自己添加的格式化器转换器,我们只需要放在容器中即可
  • HttpMessageConverter:SpringMVC用来转换Http请求和响应的;User—Json;

    • HttpMessageConverters 是从容器中确定;获取所有的HttpMessageConverter;

    自己给容器中添加HttpMessageConverter,只需要将自己的组件注册容器中(@Bean,@Component)

  • MessageCodesResolver (see below).定义错误代码生成规则

  • 我们可以配置一个ConfigurableWebBindingInitializer来替换默认的;(添加到容器)

 初始化WebDataBinder;
  请求数据=====JavaBean;

org.springframework.boot.autoconfigure.web:web的所有自动场景;

@ConditionalOnProperty(prefix=“spring.mvc”,name = “”) //配置文件中配置日期格式化的规则

tip:
内部类
1.内部类+接口 ===== c++的多继承
2.封装性
3.一个内部类对象可以访问创建它的外部类对象的内容,甚至包括私有变量!
4.静态内部类没有指向外部的引用

java的引用和指针有什么区别
1.对象在堆中分配内存,函数的参数在栈中分配
2.当创建对象或者对已经创建的对象赋值时,进行的是对象地址的传递并复制。这就是所说的句柄的传递和赋值。
3.Java把指针隐藏起来了,而不像c和c++可以获取到地址

修改SpringBoot的默认配置

  1. 先看容器中有没有用户自己配置的(@Bean、@Component),如果没有就自动配置。如果有些组件有多个ViewResolve将用户配置的和默认组合起来

编写一个配置类(@Configuration),是WebMvcConfigurerAdapter(2以上版本用WebMvcConfigurer)类型;不能标注@EnableWebMvc;

WebMvcConfigurationSupport

既保留了所有的自动配置,也能用我们扩展的配置;

原理:

​ 1)、WebMvcAutoConfiguration是SpringMVC的自动配置类

​ 2)、在做其他自动配置时会导入;@Import(EnableWebMvcConfiguration.class)
​ 3)、容器中所有的WebMvcConfigurer都会一起起作用;

​ 4)、我们的配置类也会被调用;

​ 效果:SpringMVC的自动配置和我们的扩展配置都会起作用;

全面接管SpringMVC

自己进行配置,SpringBoot对SpringMVC的自动配置失效,添加@EnableWebMvc

原理:

为什么@EnableWebMvc自动配置就失效了;

1)@EnableWebMvc的核心

@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {

2)、

@Configuration
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport 

3)、

@Configuration
@ConditionalOnWebApplication
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class,
		WebMvcConfigurerAdapter.class })
//容器中没有这个组件的时候,这个自动配置类才生效
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class,
		ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration {

4)、@EnableWebMvc将WebMvcConfigurationSupport组件导入进来;

5)、导入的WebMvcConfigurationSupport只是SpringMVC最基本的功能;

猜你喜欢

转载自blog.csdn.net/xuxuan1997/article/details/88833598
今日推荐