SpringBoot2核心技术与响应式编程
SpringBoot2核心技术
SpringBoot2基础入门
Spring能做什么?

- Spring的生态
- 覆盖了:
web开发
数据访问
安全控制
分布式
消息服务
移动开发
批处理
- Spring5的重大升级
- 内部源码设计
- 基于Java8的一些新特性,如:接口默认实现。重新设计源码架构。
什么是SpringBoot?
Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can "just run"
能快速创建出生产级别的Spring应用
SpringBoot优点
- Create stand-alone Spring applications
- Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files)
- Provide opinionated 'starter' dependencies to simplify your build configuration
- Automatically configure Spring and 3rd party libraries whenever possible
- Provide production-ready features such as metrics, health checks, and externalized configuration
- Absolutely no code generation and no requirement for XML configuration
SpringBoot是整合Spring技术栈的一站式框架
SpringBoot是简化Spring技术栈的快速开发脚手架
SpringBoot缺点
- 人称版本帝,迭代快,需要时刻关注变化
- 封装太深,内部原理复杂,不容易精通
SpringBoot时代背景
微服务
James Lewis and Martin Fowler (2014) 提出微服务完整概念。https://martinfowler.com/microservices/
In short, the microservice architectural style is an approach to developing a single application as a suite of small services, each running in its own process and communicating with lightweight mechanisms, often an HTTP resource API. These services are built around business capabilities and independently deployable by fully automated deployment machinery. There is a bare minimum of centralized management of these services, which may be written in different programming languages and use different data storage technologies.-- James Lewis and Martin Fowler (2014)
- 微服务是一种架构风格
- 一个应用拆分为一组小型服务
- 每个服务运行在自己的进程内,也就是可独立部署和升级
- 服务之间使用轻量级HTTP交互
- 服务围绕业务功能拆分
- 可以由全自动部署机制独立部署
- 去中心化,服务自治。服务可以使用不同的语言、不同的存储技术
分布式

- 分布式的困难
- 远程调用
- 服务发现
- 负载均衡
- 服务容错
- 配置管理
- 服务监控
- 链路追踪
- 日志管理
- 任务调度
分布式的解决
SpringBoot+SpringCloud

云原生
原生应用如何上云。 Cloud Native
- 上云的困难
- 服务自愈
- 弹性伸缩
- 服务隔离
- 自动化部署
- 灰度发布
- 流量治理
- ......
- 上云的解决
如何学习SpringBoot
官方文档架构

查看版本新特性;
https://github.com/spring-projects/spring-boot/wiki#release-notes

快速体验SpringBoot
系统要求
- Java 8 & 兼容java14 .
- Maven 3.3+
- idea 2019.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>
复制代码 Hello Word
需求:浏览发送/hello请求,响应 Hello,Spring Boot 2
创建maven工程
引入依赖
- <parent>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-parent</artifactId>
- <version>2.3.4.RELEASE</version>
- </parent>
- <dependencies>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
- </dependencies>
复制代码 创建主程序
- package com.lkjedu.boot;
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- /**
- * 主程序类
- * @SpringBootApplication:告诉SpringBoot这是一个SpringBoot应用
- *
- * */
- @SpringBootApplication
- public class MainApplication {
- public static void main(String[] args) {
- SpringApplication.run(MainApplication.class,arg s);
- }
- }
复制代码 编写业务
- package com.lkjedu.boot.controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
- @RestController
- public class HelloController {
- @RequestMapping("hello")
- public String handle01(){
- return "Hello SpringBoot2";
- }
- }
复制代码 测试
直接运行main方法
简化配置
简化部署
- <build>
- <plugins>
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- </plugin>
- </plugins>
- </build>
复制代码 把项目打成jar包,直接在目标服务器执行即可。
注意点:
依赖管理
- 依赖管理
- <parent>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-parent</artifactId>
- <version>2.3.4.RELEASE</version>
- </parent>
- 他的父项目
- <parent>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-dependencies</artifactId>
- <version>2.3.4.RELEASE</version>
- </parent>
- 几乎声明了所有开发中常用的依赖的版本号,自动版本仲裁机制
复制代码- 1、见到很多 spring-boot-starter-* : *就某种场景
- 2、只要引入starter,这个场景的所有常规需要的依赖我们都自动引入
- 3、SpringBoot所有支持的场景
- https://docs.spring.io/spring-boot/docs/current/reference/html/using-spring-boot.html#using-boot-starter
- 4、见到的 *-spring-boot-starter: 第三方为我们提供的简化开发的场景启动器。
- 5、所有场景启动器最底层的依赖
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter</artifactId>
- <version>2.3.4.RELEASE</version>
- <scope>compile</scope>
- </dependency>
复制代码 1、引入依赖默认都可以不写版本
2、引入非版本仲裁的jar,要写版本号。
- 1、查看spring-boot-dependencies里面规定当前依赖的版本 用的 key。
- 2、在当前项目里面重写配置
- <properties>
- <mysql.version>5.1.43</mysql.version>
- </properties>
复制代码 自动配置
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-tomcat</artifactId>
- <version>2.3.4.RELEASE</version>
- <scope>compile</scope>
- </dependency>
复制代码
- 自动配好SpringMVC
- 引入SpringMVC全套组件
- 自动配好SpringMVC常用组件(功能)
- 自动配好Web常见功能,如:字符编码问题
- SpringBoot帮我们配置好了所有web开发的常见场景
- 默认的包结构
- 主程序所在包及其下面的所有子包里面的组件都会被默认扫描进来
- 无需以前的包扫描配置
- 想要改变扫描路径,@SpringBootApplication(scanBasePackages="com.atguigu")
- @SpringBootApplication
- 等同于
- @SpringBootConfiguration
- @EnableAutoConfiguration
- @ComponentScan("com.atguigu.boot")
复制代码
- 各种配置拥有默认值
- 默认配置最终都是映射到某个类上,如:MultipartProperties
- 配置文件的值最终会绑定每个类上,这个类会在容器中创建对象
- 按需加载所有自动配置项
- 非常多的starter
- 引入了哪些场景这个场景的自动配置才会开启
- SpringBoot所有的自动配置功能都在 spring-boot-autoconfigure 包里面
- ......
容器功能
1、@Configuration
- 基本使用
- Full模式与Lite模式
- 配置 类组件之间无依赖关系用Lite模式加速容器启动过程,减少判断
- 配置类组件之间有依赖关系,方法会被调用得到之前单实例组件,用Full模式
- #############################Configuration使用示例######################################################
- /**
- * 1、配置类里面使用@Bean标注在方法上给容器注册组件,默认也是单实例的
- * 2、配置类本身也是组件
- * 3、proxyBeanMethods:代理bean的方法
- * Full(proxyBeanMethods = true)、【保证每个@Bean方法被调用多少次返回的组件都是单实例的】
- * Lite(proxyBeanMethods = false)【每个@Bean方法被调用多少次返回的组件都是新创建的】
- * 组件依赖必须使用Full模式默认。其他默认是否Lite模式
- *
- *
- *
- */
- @Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类 == 配置文件
- public class MyConfig {
- /**
- * Full:外部无论对配置类中的这个组件注册方法调用多少次获取的都是之前注册容器中的单实例对象
- * @return
- */
- @Bean //给容器中添加组件。以方法名作为组件的id。返回类型就是组件类型。返回的值,就是组件在容器中的实例
- public User user01(){
- User zhangsan = new User("zhangsan", 18);
- //user组件依赖了Pet组件
- zhangsan.setPet(tomcatPet());
- return zhangsan;
- }
- @Bean("tom")
- public Pet tomcatPet(){
- return new Pet("tomcat");
- }
- }
- ################################@Configuration测试代码如下########################################
- @SpringBootConfiguration
- @EnableAutoConfiguration
- @ComponentScan("com.atguigu.boot")
- public class MainApplication {
- public static void main(String[] args) {
- //1、返回我们IOC容器
- ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);
- //2、查看容器里面的组件
- String[] names = run.getBeanDefinitionNames();
- for (String name : names) {
- System.out.println(name);
- }
- //3、从容器中获取组件
- Pet tom01 = run.getBean("tom", Pet.class);
- Pet tom02 = run.getBean("tom", Pet.class);
- System.out.println("组件:"+(tom01 == tom02));
- //4、com.atguigu.boot.config.MyConfig$$EnhancerBySpringCGLIB$$51f1e1ca@1654a892
- MyConfig bean = run.getBean(MyConfig.class);
- System.out.println(bean);
- //如果@Configuration(proxyBeanMethods = true)代理对象调用方法。SpringBoot总会检查这个组件是否在容器中有。
- //保持组件单实例
- User user = bean.user01();
- User user1 = bean.user01();
- System.out.println(user == user1);
- User user01 = run.getBean("user01", User.class);
- Pet tom = run.getBean("tom", Pet.class);
- System.out.println("用户的宠物:"+(user01.getPet() == tom));
- }
- }
复制代码 2@Bean、@Component、@Controller、@Service、@Repository
- * 4、@Import({User.class, DBHelper.class})
- * 给容器中自动创建出这两个类型的组件、默认组件的名字就是全类名
- *
- *
- *
- */
- @Import({User.class, DBHelper.class})
- @Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类 == 配置文件
- public class MyConfig {
- }
复制代码 @Import 高级用法: https://www.bilibili.com/video/BV1gW411W7wy?p=8
3、@ComponentScan、@Import
- * 4、@Import({User.class, DBHelper.class})
- * 给容器中自动创建出这两个类型的组件、默认组件的名字就是全类名
- *
- *
- *
- */
- @Import({User.class, DBHelper.class})
- @Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类 == 配置文件
- public class MyConfig {
- }
复制代码 @Import 高级用法: https://www.bilibili.com/video/BV1gW411W7wy?p=8
4、@Conditional
条件装配:满足Conditional指定的条件,则进行组件注入
 - =====================测试条件装配==========================
- @Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类 == 配置文件
- //@ConditionalOnBean(name = "tom")
- @ConditionalOnMissingBean(name = "tom")
- public class MyConfig {
- /**
- * Full:外部无论对配置类中的这个组件注册方法调用多少次获取的都是之前注册容器中的单实例对象
- * @return
- */
- @Bean //给容器中添加组件。以方法名作为组件的id。返回类型就是组件类型。返回的值,就是组件在容器中的实例
- public User user01(){
- User zhangsan = new User("zhangsan", 18);
- //user组件依赖了Pet组件
- zhangsan.setPet(tomcatPet());
- return zhangsan;
- }
- @Bean("tom22")
- public Pet tomcatPet(){
- return new Pet("tomcat");
- }
- }
- public static void main(String[] args) {
- //1、返回我们IOC容器
- ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);
- //2、查看容器里面的组件
- String[] names = run.getBeanDefinitionNames();
- for (String name : names) {
- System.out.println(name);
- }
- boolean tom = run.containsBean("tom");
- System.out.println("容器中Tom组件:"+tom);
- boolean user01 = run.containsBean("user01");
- System.out.println("容器中user01组件:"+user01);
- boolean tom22 = run.containsBean("tom22");
- System.out.println("容器中tom22组件:"+tom22);
- }
复制代码 2.2、原生配置文件引入
- @ImportResource
- ======================beans.xml=========================
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:context="http://www.springframework.org/schema/context"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
- <bean id="haha" >
- <property name="name" value="zhangsan"></property>
- <property name="age" value="18"></property>
- </bean>
- <bean id="hehe" >
- <property name="name" value="tomcat"></property>
- </bean>
- </beans>
复制代码- @ImportResource("classpath:beans.xml")
- public class MyConfig {}
- ======================测试=================
- boolean haha = run.containsBean("haha");
- boolean hehe = run.containsBean("hehe");
- System.out.println("haha:"+haha);//true
- System.out.println("hehe:"+hehe);//true
复制代码
@ConfigurationProperties
如何使用Java读取到properties文件中的内容,并且把它封装到JavaBean中,以供随时使用;- public class getProperties {
- public static void main(String[] args) throws FileNotFoundException, IOException {
- Properties pps = new Properties();
- pps.load(new FileInputStream("a.properties"));
- Enumeration enum1 = pps.propertyNames();//得到配置文件的名字
- while(enum1.hasMoreElements()) {
- String strKey = (String) enum1.nextElement();
- String strValue = pps.getProperty(strKey);
- System.out.println(strKey + "=" + strValue);
- //封装到JavaBean。
- }
- }
- }
复制代码
- @Component + @ConfigurationProperties
- @EnableConfigurationProperties + @ConfigurationProperties
- @EnableConfigurationProperties(Car.class)
- //1、开启Car配置绑定功能
- //2、把这个Car这个组件自动注册到容器中
- public class MyConfig {
- }
复制代码
-
- ##### 自动配置原理
- ###### 引导加载自动配置类
- ~~~Java
- @SpringBootConfiguration
- @EnableAutoConfiguration
- @ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
- @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
- public @interface SpringBootApplication{}
- ======================
-
复制代码 @SpringBootConfiguration
@Configuration:代表当前是一个配置类
@ComponentScan
指定我们扫描那些包
@EnableAutoConfiguration
启用 SpringBoot 的自动配置机制- //也是两个注解的合成注解
- @AutoConfigurationPackage
- @Import({AutoConfigurationImportSelector.class})
- public @interface EnableAutoConfiguration {}
复制代码
- @AutoConfigurationPackage:
- 自动配置包
- @Import(AutoConfigurationPackages.Registrar.class) //给容器中导入一个组件
- public @interface AutoConfigurationPackage {}
- //利用Registrar给容器中导入一系列组件
- //将指定的一个包下的所有组件导入进来?MainApplication 所在包下。
复制代码
- @Import(AutoConfigurationImportSelector.class)
- 1、利用getAutoConfigurationEntry(annotationMetadata);给容器中批量导入一些组件
- 2、调用List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes)获取到所有需要导入到容器中的配置类
- 3、利用工厂加载 Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader);得到所有的组件
- 4、从META-INF/spring.factories位置来加载一个文件。
- 默认扫描我们当前系统里面所有META-INF/spring.factories位置的文件
- spring-boot-autoconfigure-2.3.4.RELEASE.jar包里面也有META-INF/spring.factories
-
复制代码
按需开启自动配置项
- 虽然我们127个场景的所有自动配置启动的时候默认全部加载。xxxxAutoConfiguration
- 按照条件装配规则(@Conditional),最终会按需配置。
复制代码 修改默认配置
- @Bean
- @ConditionalOnBean(MultipartResolver.class) //容器中有这个类型组件
- @ConditionalOnMissingBean(name = DispatcherServlet.MULTIPART_RESOLVER_BEAN_NAME) //容器中没有这个名字 multipartResolver 的组件
- public MultipartResolver multipartResolver(MultipartResolver resolver) {
- //给@Bean标注的方法传入了对象参数,这个参数的值就会从容器中找。
- //SpringMVC multipartResolver。防止有些用户配置的文件上传解析器不符合规范
- // Detect if the user has created a MultipartResolver but named it incorrectly
- return resolver;
- }
- 给容器中加入了文件上传解析器;
复制代码 SpringBoot默认会在底层配好所有的组件。但是如果用户自己配置了以用户的优先- @Bean
- @ConditionalOnMissingBean
- public CharacterEncodingFilter characterEncodingFilter() {
- }
复制代码 总结:- ● SpringBoot先加载所有的自动配置类 xxxxxAutoConfiguration
- ● 每个自动配置类按照条件进行生效,默认都会绑定配置文件指定的值。xxxxProperties里面拿。xxxProperties和配置文件进行了绑定
- ● 生效的配置类就会给容器中装配很多组件
- ● 只要容器中有这些组件,相当于这些功能就有了
- ● 定制化配置
- ○ 用户直接自己@Bean替换底层的组件
- ○ 用户去看这个组件是获取的配置文件什么值就去修改。
- xxxxxAutoConfiguration ---> 组件 ---> xxxxProperties里面拿值 ----> application.properties
复制代码 最佳实践
- 引入场景依赖
- 查看自动配置了哪些(选做)
- 自己分析,引入场景对应的自动配置一般都生效了
- 配置文件中debug=true开启自动配置报告。Negative(不生效)\Positive(生效)
- 是否需要修改
- 自定义器 XXXXXCustomizer;
- ......
开发小技巧
Lombok
- import lombok.Data(@Data):生成已有属性的geter和seter方法
- import lombok.ToString(@ToString):生成已有属性的toString方法
- import lombok.NoArgsConstructor(@NoArgsConstructor):生成已有属性的无参构造器
- import lombok.AllArgsConstructor(@AllArgsConstructor):生成已有属性的全参构造器
- import lombok.EqualsAndHashCode(@EqualsAndHashCode):重写我们的Equals和HashCode方法
- import lombok.slf4j(@slf4j):相当于我们的日志类
- <dependency>
- <groupId>org.projectlombok</groupId>
- <artifactId>lombok</artifactId>
- </dependency>
- idea中搜索安装lombok插件
复制代码- ===============================简化JavaBean开发===================================
- @NoArgsConstructor
- //@AllArgsConstructor
- @Data
- @ToString
- @EqualsAndHashCode
- public class User {
- private String name;
- private Integer age;
- private Pet pet;
- public User(String name,Integer age){
- this.name = name;
- this.age = age;
- }
- }
- ================================简化日志开发===================================
- @Slf4j
- @RestController
- public class HelloController {
- @RequestMapping("/hello")
- public String handle01(@RequestParam("name") String name){
-
- log.info("请求进来了....");
-
- return "Hello, Spring Boot 2!"+"你好:"+name;
- }
- }
复制代码 dev-tools
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-devtools</artifactId>
- <optional>true</optional>
- </dependency>
复制代码 项目或者页面修改以后:Ctrl+F9;
Spring Initailizr(项目初始化向导)
- 选择我们需要的开发场景
2.1、自动依赖引入

- 自动创建项目结构
4.自动编写好主配置类

1、自动依赖引入
SpringBoot2核心功能
配置文件
文件类型
properties
同以前的properties用法
yaml
- 简介
- YAML 是 "YAML Ain't Markup Language"(YAML 不是一种标记语言)的递归缩写。在开发的这种语言时,YAML 的意思其实是:"Yet Another Markup Language"(仍是一种标记语言)。非常适合用来做以数据为中心的配置文件
- 基本语法
- key: value;kv之间有空格
- 大小写敏感
- 使用缩进表示层级关系
- 缩进不允许使用tab,只允许空格
- 缩进的空格数不重要,只要相同层级的元素左对齐即可
- '#'表示注释
- 字符串无需加引号,如果要加,''与""表示字符串内容 会被 转义/不转义
- 数据类型
- 字面量:单个的、不可再分的值。date、boolean、string、number、null
- 对象:键值对的集合。map、hash、set、object
- 行内写法: k: {k1:v1,k2:v2,k3:v3}
- #或
- k:
- k1: v1
- k2: v2
- k3: v3
复制代码- 数组:一组按次序排列的值。array、list、queue
- 行内写法: k: [v1,v2,v3]
- #或者
- k:
- - v1
- - v2
- - v3
复制代码- 提示:
- 在yaml文件格里面式,单引号会将“\n”简单的字符串输出
- 在yaml文件格里面式,双引号会将“\n”则会作为转义符
配置提示
自定义的类和配置文件绑定一般没有提示。- org.springframework.boot spring-boot-configuration-processor true <build>
- <plugins>
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- </plugin>
- </plugins>
- </build> org.springframework.boot spring-boot-configuration-processor
复制代码 web开发
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.
- Support for serving static resources, including support for WebJars (covered later in this document)).
- 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.
- Custom Favicon support (covered later in this document).
- 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**
简单功能分析
静态资源访问
- 静态资源目录
只要静态资源放在类路径下: called /static (or /public or /resources or /META-INF/resources
访问:当前项目根路径/+静态资源名
原理:静态映射/**
请求进来先去找Controller看能不能处理。不能处理的所有请求又都交给静态资源处理器。静态资源也找不到则直接报404
改变默认的静态资源路径- spring:
- mvc:
- static-path-pattern: /res/**
- #改变姿态资源路径
- resources:
- static-locations: [classpath:/haha/]
复制代码 - 静态资源访问前缀
默认无前缀- spring:
- mvc:
- static-path-pattern: /res/**
复制代码 - webjar
自动映射 /webjars/**
https://www.webjars.org/- <dependency>
- <groupId>org.webjars</groupId>
- <artifactId>jquery</artifactId>
- <version>3.5.1</version>
- </dependency>
复制代码 访问地址:http://localhost:8080/webjars/jquery/3.5.1/jquery.js 后面地址要按照依赖里面的包路径
欢迎页支持
- 静态资源路径下 index.html
- 可以配置静态资源路径
- 但是不可以配置静态资源的访问前缀。否则导致 index.html不能被默认访问
- spring:
- # mvc:
- # static-path-pattern: /res/** 这个会导致welcome page功能失效
- resources:
- static-locations: [classpath:/haha/]
复制代码 2.3、自定义 Favicon
favicon.ico 放在静态资源目录下即可。- spring:
- # mvc:
- # static-path-pattern: /res/** 这个会导致 Favicon 功能失效
复制代码 静态资源配置原理
- SpringBoot启动默认加载 xxxAutoConfiguration 类(自动配置类)
- SpringMVC功能的自动配置类 WebMvcAutoConfiguration,生效
- @Configuration(proxyBeanMethods = false)
- @ConditionalOnWebApplication(type = Type.SERVLET)
- @ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class })
- @ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
- @AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
- @AutoConfigureAfter({ DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class,
- ValidationAutoConfiguration.class })
- public class WebMvcAutoConfiguration {}
复制代码- @Configuration(proxyBeanMethods = false)
- @Import(EnableWebMvcConfiguration.class)
- @EnableConfigurationProperties({ WebMvcProperties.class, ResourceProperties.class })
- @Order(0)
- public static class WebMvcAutoConfigurationAdapter implements WebMvcConfigurer {}
复制代码
- 配置文件的相关属性和xxx进行了绑定。WebMvcPropertiesspring.mvc、ResourcePropertiesspring.resources
配置类只有一个有参构造器- //有参构造器所有参数的值都会从容器中确定
- //ResourceProperties resourceProperties;获取和spring.resources绑定的所有的值的对象
- //WebMvcProperties mvcProperties 获取和spring.mvc绑定的所有的值的对象
- //ListableBeanFactory beanFactory Spring的beanFactory
- //HttpMessageConverters 找到所有的HttpMessageConverters
- //ResourceHandlerRegistrationCustomizer 找到 资源处理器的自定义器。=========
- //DispatcherServletPath
- //ServletRegistrationBean 给应用注册Servlet、Filter....
- public WebMvcAutoConfigurationAdapter(ResourceProperties resourceProperties, WebMvcProperties mvcProperties,
- ListableBeanFactory beanFactory, ObjectProvider<HttpMessageConverters> messageConvertersProvider,
- ObjectProvider<ResourceHandlerRegistrationCustomizer> resourceHandlerRegistrationCustomizerProvider,
- ObjectProvider<DispatcherServletPath> dispatcherServletPath,
- ObjectProvider<ServletRegistrationBean<?>> servletRegistrations) {
- this.resourceProperties = resourceProperties;
- this.mvcProperties = mvcProperties;
- this.beanFactory = beanFactory;
- this.messageConvertersProvider = messageConvertersProvider;
- this.resourceHandlerRegistrationCustomizer = resourceHandlerRegistrationCustomizerProvider.getIfAvailable();
- this.dispatcherServletPath = dispatcherServletPath;
- this.servletRegistrations = servletRegistrations;
- }
复制代码 配置 private Configuration configuration; mybatis.configuration下面的所有,就是相当于改mybatis全局配置文件中的值- spring:
- # mvc:
- # static-path-pattern: /res/**
- resources:
- add-mappings: false 禁用所有静态资源规则
复制代码
- 导入mybatis官方starter
- 编写mapper接口。标准@Mapper注解
- 编写sql映射文件并绑定mapper接口
- 在application.yaml中指定Mapper配置文件的位置,以及指定全局配置文件的信息 (建议;配置在mybatis.configuration)
2.注解模式- @ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
- public class ResourceProperties {
- private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/",
- "classpath:/resources/", "classpath:/static/", "classpath:/public/" };
- /**
- * Locations of static resources. Defaults to classpath:[/META-INF/resources/,
- * /resources/, /static/, /public/].
- */
- private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
复制代码 3.混合模式- @ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
- public class ResourceProperties {
- private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/",
- "classpath:/resources/", "classpath:/static/", "classpath:/public/" };
- /**
- * Locations of static resources. Defaults to classpath:[/META-INF/resources/,
- * /resources/, /static/, /public/].
- */
- private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
复制代码 最佳实战:
- 引入mybatis-starter
- 配置application.yaml中,指定mapper-location位置即可
- 编写Mapper接口并标注@Mapper注解
- 简单方法直接注解方式
- 复杂方法编写mapper.xml进行绑定映射
- @MapperScan("com.atguigu.admin.mapper") 简化,其他的接口就可以不用标注@Mapper注解
4、整合 MyBatis-Plus 完成CRUD
- 什么是MyBatis-Plus
- 整合MyBatis-Plus
- @RequestMapping(value = "/user",method = RequestMethod.GET)
- public String getUser(){
- return "GET-张三";
- }
- @RequestMapping(value = "/user",method = RequestMethod.POST)
- public String saveUser(){
- return "POST-张三";
- }
- @RequestMapping(value = "/user",method = RequestMethod.PUT)
- public String putUser(){
- return "PUT-张三";
- }
- @RequestMapping(value = "/user",method = RequestMethod.DELETE)
- public String deleteUser(){
- return "DELETE-张三";
- }
- @Bean
- @ConditionalOnMissingBean(HiddenHttpMethodFilter.class)
- @ConditionalOnProperty(prefix = "spring.mvc.hiddenmethod.filter", name = "enabled", matchIfMissing = false)
- public OrderedHiddenHttpMethodFilter hiddenHttpMethodFilter() {
- return new OrderedHiddenHttpMethodFilter();
- }
- //自定义filter
- @Bean
- public HiddenHttpMethodFilter hiddenHttpMethodFilter(){
- HiddenHttpMethodFilter methodFilter = new HiddenHttpMethodFilter();
- methodFilter.setMethodParam("_m");
- return methodFilter;
- }
复制代码- 自动配置
- MybatisPlusAutoConfiguration 配置类,MybatisPlusProperties 配置项绑定。mybatis-plus:xxx 就是对****mybatis-plus的定制
- SqlSessionFactory 自动配置好。底层是容器中默认的数据源
- mapperLocations 自动配置好的。有默认值。***classpath*:/mapper/*/*.xml;任意包的类路径下的所有mapper文件夹下任意路径下的所有xml都是sql映射文件。 建议以后sql映射文件,放在 mapper下
- 容器中也自动配置好了 SqlSessionTemplate
- @Mapper 标注的接口也会被自动扫描;建议直接 @MapperScan("com.atguigu.admin.mapper") 批量扫描就行
- 优点:
- 只需要我们的Mapper继承 BaseMapper 就可以拥有crud能力
- CRUD功能
- spring:
- mvc:
- hiddenmethod:
- filter:
- enabled: true #开启页面表单的Rest功能
复制代码- protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
- HttpServletRequest processedRequest = request;
- HandlerExecutionChain mappedHandler = null;
- boolean multipartRequestParsed = false;
- WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
- try {
- ModelAndView mv = null;
- Exception dispatchException = null;
- try {
- processedRequest = checkMultipart(request);
- multipartRequestParsed = (processedRequest != request);
- // 找到当前请求使用哪个Handler(Controller的方法)处理
- mappedHandler = getHandler(processedRequest);
-
- //HandlerMapping:处理器映射。/xxx->>xxxx
复制代码
NoSQL
Redis 是一个开源(BSD许可)的,内存中的数据结构存储系统,它可以用作数据库、缓存和消息中间件。 它支持多种类型的数据结构,如 字符串(strings), 散列(hashes), 列表(lists), 集合(sets), 有序集合(sorted sets) 与范围查询, bitmaps, hyperloglogs 和 地理空间(geospatial) 索引半径查询。 Redis 内置了 复制(replication),LUA脚本(Lua scripting), LRU驱动事件(LRU eviction),事务(transactions) 和不同级别的 磁盘持久化(persistence), 并通过 Redis哨兵(Sentinel)和自动 分区(Cluster)提供高可用性(high availability)。
1、Redis自动配置
- protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
- if (this.handlerMappings != null) {
- for (HandlerMapping mapping : this.handlerMappings) {
- HandlerExecutionChain handler = mapping.getHandler(request);
- if (handler != null) {
- return handler;
- }
- }
- }
- return null;
- }
复制代码
自动配置:
- RedisAutoConfiguration 自动配置类。RedisProperties 属性类 --> spring.redis.xxx是对redis的配置
- 连接工厂是准备好的。LettuceConnectionConfiguration、JedisConnectionConfiguration
- 自动注入了RedisTemplate : xxxTemplate;
- 自动注入了StringRedisTemplate;k:v都是String
- key:value
- 底层只要我们使用 StringRedisTemplate、****RedisTemplate就可以操作redis
redis环境搭建
1、阿里云按量付费redis。经典网络
2、申请redis的公网连接地址
3、修改白名单 允许0.0.0.0/0 访问
2、RedisTemplate与Lettuce
- @Configuration
- public class SpringBootConfig implements WebMvcConfigurer {
- @Override
- public void configurePathMatch(PathMatchConfigurer configurer) {
- UrlPathHelper urlPathHelper = new UrlPathHelper();
- urlPathHelper.setRemoveSemicolonContent(false);
- configurer.setUrlPathHelper(urlPathHelper);
- }
- }
复制代码 3、切换至jedis
- protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
- if (this.handlerMappings != null) {
- for (HandlerMapping mapping : this.handlerMappings) {
- HandlerExecutionChain handler = mapping.getHandler(request);
- if (handler != null) {
- return handler;
- }
- }
- }
- return null;
- } redis.clients jedis
复制代码- @Override
- public boolean supportsParameter(MethodParameter parameter) {
- Class<?> paramType = parameter.getParameterType();
- return (WebRequest.class.isAssignableFrom(paramType) ||
- ServletRequest.class.isAssignableFrom(paramType) ||
- MultipartRequest.class.isAssignableFrom(paramType) ||
- HttpSession.class.isAssignableFrom(paramType) ||
- (pushBuilder != null && pushBuilder.isAssignableFrom(paramType)) ||
- Principal.class.isAssignableFrom(paramType) ||
- InputStream.class.isAssignableFrom(paramType) ||
- Reader.class.isAssignableFrom(paramType) ||
- HttpMethod.class == paramType ||
- Locale.class == paramType ||
- TimeZone.class == paramType ||
- ZoneId.class == paramType);
- }
复制代码 JUnit5单元测试
生产指标监控
SpringBoot核心原理解析
SpringBoot2场景整合
虚拟化技术
安全控制
缓存技术
消息中间件
分布式入门
SpringBoot2响应式编程
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |