springboot

1、hello,springboot

官方文档:https://docs.spring.io/spring-boot/docs/2.5.6/reference/htmlsingle/#getting-started

版本更新:https://github.com/spring-projects/spring-boot/wiki#release-notes

1.1系统要求

  • Java 8 & 兼容java14 .

  • Maven 3.3+

  • idea 2019.1.2

1.2 Maven设置

<mirrors>
      <mirror>
        <id>nexus-aliyun</id>
        <mirrorOf>central</mirrorOf>
        <name>Nexus aliyun</name>
        <url>http://maven.aliyun.com/nexus/content/groups/public</url>
      </mirror>
  </mirrors>

  <profiles>
         <profile>
              <id>jdk-1.8</id>
              <activation>
                <activeByDefault>true</activeByDefault>
                <jdk>1.8</jdk>
              </activation>
              <properties>
                <maven.compiler.source>1.8</maven.compiler.source>
                <maven.compiler.target>1.8</maven.compiler.target>
                <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
              </properties>
         </profile>
  </profiles>

1.3引入依赖

1.4主程序

1.5编写业务

1.6测试

直接运行main()方法

1.7简化配置

application.properties

1.8简化部署

把项目打成jar包,直接在目标服务器执行即可。

注意点:

  • 取消掉cmd的快速编辑模式,有时候光标放在命令行中就会等待编辑不会运行

2、自动配置

2.1依赖管理

  • 父项目做依赖管理

  • 开发导入starter场景启动器

  • 无需关注版本号,自动版本仲裁

  • 可以修改默认版本号

2.2 自动配置

  • 自动配好Tomcat

    • 引入Tomcat依赖

    • 配置Tomcat

  • 自动配好SpringMVC

    • 引入SpringMVC全套组件

    • 自动配好SpringMVC常用组件(功能)

  • 自动配好Web常见功能,如:字符编码问题

    • SpringBoot帮我们配置好了所有web开发的常见场景

  • 默认的包结构

    • 主程序所在包及其下面的所有子包里面的组件都会被默认扫描进来

    • 无需以前的包扫描配置

    • 想要改变扫描路径,@SpringBootApplication(scanBasePackages="com.atguigu")

      • 或者@ComponentScan 指定扫描路径

  • 各种配置拥有默认值

    • 默认配置最终都是映射到某个类上,如:MultipartProperties

    • 配置文件的值最终会绑定每个类上,这个类会在容器中创建对象

  • 按需加载所有自动配置项

    • 非常多的starter

    • 引入了哪些场景这个场景的自动配置才会开启

    • SpringBoot所有的自动配置功能都在 spring-boot-autoconfigure 包里面

3、容器功能

3.1 组件添加

1、@Configuration

  • 基本使用

  • Full模式与Lite模式

    • 示例

    • 最佳实战

      • 配置 类组件之间无依赖关系用Lite模式加速容器启动过程,减少判断

      • 配置类组件之间有依赖关系,方法会被调用得到之前单实例组件,用Full模式

2、@Bean、@Component、@Controller、@Service、@Repository

这些组件的用法都和SpringMVC中相同,只要被扫描到就可以使用

3、@ComponentScan、@Import

@ComponentScan前面也已经说了,被主方法@SpringBootApplication兼并了

4、@Conditional

条件装配:满足Conditional指定的条件,则进行组件注入

img

5、@ImportResource

6、@configurationProperites

这个注解可以将写在配置文件里面的属性和类进行绑定

另一种方式:

4、自动配置原理

4.1 引导加载自动配置类

1、@SpringBootConfiguration

@Configuration.代表当前是一个配置类

2、@ComponentScan

指定扫描哪些,spring注解

3、EnableAutoConfiguration

1 @AutoConfigurationPackage

自动配置包,指定了默认的包规则

2、@Import(AutoConfigurationImportSelector.class)

AutoConfigurationImportSelector

image-20211025163626715

4.2 按需开启自动装配

4.3 修改默认配置

SpringBoot默认会在底层配好所有的组件。但是如果用户自己配置了以用户的优先

总结:

  • SpringBoot先加载所有的自动配置类 xxxxxAutoConfiguration

  • 每个自动配置类按照条件进行生效,默认都会绑定配置文件指定的值。xxxxProperties里面拿。xxxProperties和配置文件进行了绑定

  • 生效的配置类就会给容器中装配很多组件

  • 只要容器中有这些组件,相当于这些功能就有了

  • 定制化配置

    • 用户直接自己@Bean替换底层的组件

    • 用户去看这个组件是获取的配置文件什么值就去修改。

xxxxxAutoConfiguration ---> 组件 ---> xxxxProperties里面拿值 ----> application.properties

4.4、最佳实践

  • 引入场景依赖

    • https://docs.spring.io/spring-boot/docs/current/reference/html/using-spring-boot.html#using-boot-starter

  • 查看自动配置了哪些(选做)

    • 自己分析,引入场景对应的自动配置一般都生效了

    • 配置文件中debug=true开启自动配置报告。Negative(不生效)\Positive(生效)

  • 是否需要修改

    • 参照文档修改配置项

      • https://docs.spring.io/spring-boot/docs/current/reference/html/appendix-application-properties.html#common-application-properties

      • 自己分析。xxxxProperties绑定了配置文件的哪些。

    • 自定义加入或者替换组件

      • @Bean、@Component。。。

    • 自定义器 XXXXXCustomizer

5、开发小技巧

5.1、LomBok

简化JavaBean开发

5.2、dev-tools

ctrl+F9 热加载(其实是重新启动,基本和idea里面点击重启一样,在后面静态页面会便捷一些直接更新)

5.3、spring initializr(项目初始化向导)

1、选择我们需要的开发场景

image.png

2、自动创建项目结构image.png

3、自动编写好主配置类

image.png

以后我们写spring boot项目直接使用这个创建,我们专注于业务就可以了

6、配置文件

1、文件类型

1.1 properties

1.2 yaml

1.2.1、简介

YAML 是 "YAML Ain't Markup Language"(YAML 不是一种标记语言)的递归缩写。在开发的这种语言时,YAML 的意思其实是:"Yet Another Markup Language"(仍是一种标记语言)。

非常适合用来做以数据为中心的配置文件

1.2.2、基本语法

  • key: value;kv之间有空格

  • 大小写敏感

  • 使用缩进表示层级关系

  • 缩进不允许使用tab,只允许空格

  • 缩进的空格数不重要,只要相同层级的元素左对齐即可

  • '#'表示注释

  • 字符串无需加引号,如果要加,''与""表示字符串内容 会被 转义/不转义

1.2.3、数据类型

  • 字面量:单个的、不可再分的值。date、boolean、string、number、null

  • 对象:键值对的集合。map、hash、set、object

  • 数组:一组按次序排列的值。array、list、queue

1.2.4、示例

2、配置提示

自定义的类和配置文件绑定一般没有提示。

7、Web开发

1、springMVC自动配置概览

Spring Boot provides auto-configuration for Spring MVC that works well with most applications.(大多场景我们都无需自定义配置)

The auto-configuration adds the following features on top of Spring’s defaults:

  • Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans.

    • 内容协商视图解析器和BeanName视图解析器

  • Support for serving static resources, including support for WebJars (covered later in this document)).

    • 静态资源(包括webjars)

  • Automatic registration of Converter, GenericConverter, and Formatter beans.

    • 自动注册 Converter,GenericConverter,Formatter

  • Support for HttpMessageConverters (covered later in this document).

    • 支持 HttpMessageConverters (后来我们配合内容协商理解原理)

  • Automatic registration of MessageCodesResolver (covered later in this document).

    • 自动注册 MessageCodesResolver (国际化用)

  • Static index.html support.

    • 静态index.html 页支持

  • Custom Favicon support (covered later in this document).

    • 自定义 Favicon

  • Automatic use of a ConfigurableWebBindingInitializer bean (covered later in this document).

    • 自动使用 ConfigurableWebBindingInitializer ,(DataBinder负责将请求数据绑定到JavaBean上)

If you want to keep those Spring Boot MVC customizations and make more MVC customizations (interceptors, formatters, view controllers, and other features), you can add your own @Configuration class of type WebMvcConfigurer but without @EnableWebMvc.

不用@EnableWebMvc注解。使用 **@Configuration** + **WebMvcConfigurer** 自定义规则

If you want to provide custom instances of RequestMappingHandlerMapping, RequestMappingHandlerAdapter, or ExceptionHandlerExceptionResolver, and still keep the Spring Boot MVC customizations, you can declare a bean of type WebMvcRegistrations and use it to provide custom instances of those components.

声明 **WebMvcRegistrations** 改变默认底层组件

If you want to take complete control of Spring MVC, you can add your own @Configuration annotated with @EnableWebMvc, or alternatively add your own @Configuration-annotated DelegatingWebMvcConfiguration as described in the Javadoc of @EnableWebMvc.

使用 **@EnableWebMvc+@Configuration+DelegatingWebMvcConfiguration 全面接管SpringMVC**

2、简单功能分析

2.1、静态资源访问

1、静态资源目录

只要静态资源在类路径下:called /static (or /public or /resources or /META-INF/resources

访问 : 当前项目根路径/ + 静态资源名

原理:静态映射/**

请求进来,先去找Controller看能不能处理,不难处理的所有请求又都交给静态资源处理器。静态资源也找不到则响应404页面

改变默认静态资源啊路径

2、静态资源访问前缀

默认无前缀

当前项目+static-path-pattern +静态资源名 = 静态资源文件夹下找

3、webjar

自动映射/webjar/**

https://www.webjars.org/

访问地址:http://localhost:8080/webjars/jquery/3.5.1/jquery.js 后面地址要按照依赖里面的包路径

webjar是自动映射所有静态资源访问前缀对它无影响,当然加上也没有影响

2.2、欢迎页支持

  • 静态资源路径下 index.html

    • 可以配置静态资源路径

    • 但是不可以配置静态资源的访问前缀。否则导致 index.html不能被默认访问

  • Controller能处理/index

spring boot中设置有限查找controller请求中的/index,controller处理不了再去静态资源中找

2.3、自定义Favicon

favicon.ico 放在静态资源目录下即可。spring boot会自动查找

2.4、静态资源配置原理

  • SpringBoot启动默认加载 xxxAutoConfiguration 类(自动配置类)

  • SpringMVC功能的自动配置类 WebMvcAutoConfiguration,生效

  • 给容器中配了什么。

  • 配置文件的相关属性和xxx进行了绑定。WebMvcProperties==spring.mvc、ResourceProperties==spring.resources

1、配置类只有一个有参构造器

2、资源处理的默认规则

3、欢迎页的处理规则

4、favicon

3、请求参数处理

1、请求映射

1.1、Rest风格使用与原理

  • @xxxMapping;

  • Rest风格支持(使用HTTP请求方式动词来表示对资源的操作

    • 以前:**/getUser 获取用户 /deleteUser 删除用户 /editUser 修改用户 /saveUser 保存用户

    • 现在: /user *GET-*获取用户 *DELETE-*删除用户 *PUT-*修改用户 *POST-*保存用户

    • 核心Filter;HiddenHttpMethodFilter

      • 用法: 表单method=post,隐藏域 _method=put

      • SpringBoot中手动开启

    • 扩展:如何把_method 这个名字换成我们自己喜欢的。

Rest原理(表单提交要使用REST的时候)

  • 表单提交会带上_method=PUT

  • 请求过来被HiddenHttpMethodFilter拦截

    • 请求是否正常,并且是POST

      • 获取到_method的值。

      • 兼容以下请求;PUT.DELETE.PATCH

      • 原生request(post),包装模式requesWrapper重写了getMethod方法,返回的是传入的值。

      • 过滤器链放行的时候用wrapper。以后的方法调用getMethod是调用****requesWrapper的。

如果不是兼容的请求就默认使用自带的GET/POST

Rest使用客户端工具,

  • 如PostMan直接发送Put、delete等方式请求,无需Filter。

  • boot后面做微服务直接提供接口即可,不一定需要页面的交互

1.2、请求映射原理

img

SpringMVC功能分析都从 org.springframework.web.servlet.DispatcherServlet-》doDispatch()

最后由doDispatch完成

image-20211028154149670

RequestMappingHandlerMapping:保存了所有@RequestMapping 和handler的映射规则。

image-20211028154348699

所有的请求映射都在HandlerMapping中

  • SpringBoot自动配置欢迎页的 WelcomePageHandlerMapping 。访问 /能访问到index.html;

  • SpringBoot自动配置了默认 的 RequestMappingHandlerMapping

  • 请求进来,挨个尝试所有的HandlerMapping看是否有请求信息。

    • 如果有就找到这个请求对应的handler

    • 如果没有就是下一个 HandlerMapping

  • 我们需要一些自定义的映射处理,我们也可以自己给容器中放HandlerMapping。自定义 HandlerMapping

5、视图解析与模板引擎

1、视图解析

1、目标方法处理的过程中,所有数据都会被放在 ModelAndViewContainer 里面。包括数据和视图地址

2、方法的参数是一个自定义类型对象(从请求参数中确定的),把他重新放在 ModelAndViewContainer

3、任何目标方法执行完成以后都会返回 ModelAndView(数据和视图地址)。

**4、**processDispatchResult 处理派发结果(页面改如何响应)

  • 1、render(mv, request, response); 进行页面渲染逻辑

    • 1、根据方法的String返回值得到 View 对象【定义了页面的渲染逻辑】

      • 1、所有的视图解析器尝试是否能根据当前返回值得到View对象

      • 2、得到了 redirect:/main.html --> Thymeleaf new RedirectView()

      • 3、ContentNegotiationViewResolver 里面包含了下面所有的视图解析器,内部还是利用下面所有视图解析器得到视图对象。

      • 4、view.render(mv.getModelInternal(), request, response); 视图对象调用自定义的render进行页面渲染工作

        • RedirectView 如何渲染【重定向到一个页面】

        • 1、获取目标url地址

        • 2、response.sendRedirect(encodedURL);

视图解析:

    • 返回值以 forward: 开始: new InternalResourceView(forwardUrl); --> 转发request.getRequestDispatcher(path).forward(request, response);

    • 返回值以 redirect: 开始: new RedirectView() --》 render就是重定向

    • 返回值是普通字符串: new ThymeleafView()--->

image.png
image.png
image.png
image.png

2、模板引擎-Thymeleaf

1、thymeleaf简介

Thymeleaf is a modern server-side Java template engine for both web and standalone environments, capable of processing HTML, XML, JavaScript, CSS and even plain text.

现代化、服务端Java模板引擎

2、基本语法

1、表达式

表达式名称
语法
用途

变量取值

${}

获取请求域、session域、对象等值

选择变量

*{}

获取上下文对象值

消息

#{}

获取国际化对象值

链接

@{}

生成链接

片段表达式

~{}

JSP:include作用,引入公共页面片段

2、字面量

文本值: 'one text' , 'Another one!' **,…**数字: 0 , 34 , 3.0 , 12.3 **,…**布尔值: true , false

空值: null

变量: one,two,.... 变量不能有空格

3、文本操作

字符串拼接: +

变量替换: |The name is ${name}|

4、数学运算

运算符: + , - , * , / , %

5、布尔运算

运算符: and , or

一元运算: ! , not

6、比较运算

比较: > , < , >= , <= ( gt , lt , ge , le **)**等式: == , != ( eq , ne )

7、条件运算

If-then: (if) ? (then)

If-then-else: (if) ? (then) : (else)

Default: (value) ?: (defaultvalue)

8、特殊操作

无操作: _

3、设置属性值-th:attr

设置单个值

设置多个值

以上两个的代替写法 th:xxxx

所有h5兼容的标签写法

https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#setting-value-to-specific-attributes

4、迭代

5、条件运算

6、属性优先级

image.png

3、thymeleaf使用

1、引入thymeleaf

2、自动配置好了thymeleaf

自动配好的策略

  • 1、所有thymeleaf的配置值都在 ThymeleafProperties

  • 2、配置好了 SpringTemplateEngine

  • 3、配好了 ThymeleafViewResolver

  • 4、我们只需要直接开发页面

3、页面开发

@{}使用链接,当你添加前缀时会自动添加进路径

最后更新于