六、流行框架介绍(SpringBoot框架详解(含底层原理介绍,适用于springBoot1.x和springBoot2.x,属于通用版本))
一、SpringBoot的概述
1.简介
Spring Boot 是 Pivotal 团队在 Spring 的基础上提供的一套全新的开源框架,其目的是为了简化 Spring 应用的搭建和开发过程。Spring Boot 去除了大量的 XML 配置文件,简化了复杂的依赖管理。
Spring Boot 具有 Spring 一切优秀特性,Spring 能做的事,Spring Boot 都可以做,而且使用更加简单,功能更加丰富,性能更加稳定而健壮。随着近些年来微服务技术的流行,Spring Boot 也成了时下炙手可热的技术。
Spring Boot 集成了大量常用的第三方库配置,Spring Boot 应用中这些第三方库几乎可以是零配置的开箱即用(out-of-the-box),大部分的 Spring Boot 应用都只需要非常少量的配置代码(基于 Java 的配置),开发者能够更加专注于业务逻辑。
2. SpringBoot的特点
● Create stand-alone Spring applications
○ 创建独立Spring应用
● Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files)
○ 内嵌web服务器
● Provide opinionated ‘starter’ dependencies to simplify your build configuration
○ 自动starter依赖,简化构建配置
● Automatically configure Spring and 3rd party libraries whenever possible
○ 自动配置Spring以及第三方功能
● Provide production-ready features such as metrics, health checks, and externalized configuration
○ 提供生产级别的监控、健康检查及外部化配置
● Absolutely no code generation and no requirement for XML configuration
○ 无代码生成、无需编写XML
SpringBoot是整合Spring技术栈的一站式框架
SpringBoot是简化Spring技术栈的快速开发脚手架
3. SpringBoot的核心功能
- 起步依赖
起步依赖本质上是一个Maven项目对象模型(Project Object Model,POM),定义了对其他库的传递依
赖,这些东西加在一起即支持某项功能。
简单的说,起步依赖就是将具备某种功能的坐标打包到一起,并提供一些默认的功能。 - 自动配置
Spring Boot的自动配置是一个运行时(更准确地说,是应用程序启动时)的过程,考虑了众多因素,才决定Spring配置应该用哪个,不该用哪个。该过程是Spring自动完成的。
二、SpringBoot入门
1. 前期准备
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>
● Java 8 & 兼容java14 .
● Maven 3.3+
2.需求
需求:浏览发送/hello请求,响应 Hello,Spring Boot 2
步骤如下:
2.1 创建maven工程
2.2 引入依赖
<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>
2.3 创建主程序
/*** 主程序类* @SpringBootApplication:这是一个SpringBoot应用*/
@SpringBootApplication
public class MainApplication {public static void main(String[] args) {SpringApplication.run(MainApplication.class,args);}
}
2.4 编写业务
//@RequestMapping
//@ResponseBody
@RestController
public class HelloController {@RequestMapping("/hello")public String handle01(){return "Hello, Spring Boot 2!";}
}
2.5 测试
直接运行main方法
2.6 简化配置
application.properties
server.port=8888
2.7 简化部署
<!‐‐ 这个插件,可以将应用打包成一个可执行的jar包;‐‐>
<build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins>
</build>
把项目打成jar包,直接在目标服务器执行即可。
注意点:
● 取消掉cmd的快速编辑模式
2.8 详细代码如下:
项目结构如下:
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.kejizhentan</groupId><artifactId>springboot-start</artifactId><version>1.0-SNAPSHOT</version><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><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>
application.properties
server.port=8888
MainApplication.java
/*** 主程序类* @SpringBootApplication:这是一个SpringBoot应用*/
@SpringBootApplication
public class MainApplication {public static void main(String[] args) {SpringApplication.run(MainApplication.class,args);}
}
HelloController.java
//@RequestMapping
//@ResponseBody
@RestController
public class HelloController {@RequestMapping("/hello")public String handle01(){return "Hello, Spring Boot 2!";}
}
效果如下:
3. Hello World探究
⑴ POM文件
①父项目
<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>
他来真正管理Spring Boot应用里面的所有依赖版本;
Spring Boot的版本仲裁中心; 以后我们导入依赖默认是不需要写版本;(没有在dependencies里面管理的依赖自然需要声明版本号)
② 启动器
<!--例如web开发的启动器-->
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency>
</dependencies>
spring-boot-starter-web
:
spring-boot-starter:spring-boot场景启动器;帮我们导入了web模块正常运行所依赖的组件;
点击获取启动器列表
Spring Boot将所有的功能场景都抽取出来,做成一个个的starters(启动器),只需要在项目里面引入这些starter 相关场景的所有依赖都会导入进来。要用什么功能就导入什么场景的启动器
⑵ 主程序类,主入口类
/*** 主程序类* @SpringBootApplication:来标注一个主程序类,说明这是一个Spring Boot应用*/
@SpringBootApplication
public class MainApplication {public static void main(String[] args) {// SpringBoot应用启动起来SpringApplication.run(MainApplication.class,args);}
}
@SpringBootApplication
: Spring Boot应用标注在某个类上说明这个类是SpringBoot的主配置类,SpringBoot 就应该运行这个类的main方法来启动SpringBoot应用;
//@SpringBootApplication是个复合注解,它包含以下注解:
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {@Filter(type = FilterType.CUSTOM,classes = {TypeExcludeFilter.class}
), @Filter(type = FilterType.CUSTOM,classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication {
① @SpringBootConfiguration:
Spring Boot的配置类;
标注在某个类上,表示这是一个Spring Boot的配置类;
@Configuration:
配置类上来标注这个注解;
配置类 ----- 配置文件;配置类也是容器中的一个组件;@Component
② @EnableAutoConfiguration
:开启自动配置功能;
以前我们需要配置的东西,Spring Boot帮我们自动配置;@EnableAutoConfiguration
告诉SpringBoot开启自 动配置功能;这样自动配置才能生效;
//@EnableAutoConfiguration也是个复合注解,它包含注解如下:
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import({AutoConfigurationImportSelector.class})
@AutoConfigurationPackage
:自动配置包//@AutoConfigurationPackage也是个组合注解,其包含的注解如下: @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @Import({Registrar.class})
@Import({Registrar.class})
Spring的底层注解@Import,给容器中导入一个组件;Registrar.class
组件的主要功能是将主配置类(@SpringBootApplication标注的类)的所在包及下面所有子包里面的所有组件扫描到Spring容器;@Import(EnableAutoConfigurationImportSelector.class);
给容器中导入组件?
EnableAutoConfigurationImportSelector
:导入哪些组件的选择器;将所有需要导入的组件以全类名的方式返回;这些组件就会被添加到容器中;
会给容器中导入非常多的自动配置类(xxxAutoConfiguration
);就是给容器中导入这个场景需要的所有组件, 并配置好这些组件;
有了自动配置类,免去了我们手动编写配置注入功能组件等的工作;自动配置类实现原理如下:
主要通过SpringFactoriesLoader.loadFactoryNames(EnableAutoConfiguration.class,classLoader);
实现的:
Spring Boot在启动的时候从类路径下的META-INF/spring.factories中获取EnableAutoConfiguration指定的值,将 这些值作为自动配置类导入到容器中,自动配置类就生效,帮我们进行自动配置工作;以前我们需要自己配置的东 西,自动配置类都帮我们;
J2EE的整体整合解决方案和自动配置都在spring-boot-autoconfigure-2.3.4.RELEASE.jar;下
4. 使用Spring Initializer快速创建Spring Boot项目
idea最长用的方式,但是得特别注意将默认的网址换成阿里的,因为外网访问比较慢,可能会失败。
具体的操作如下:
IDE都支持使用Spring的项目创建向导快速创建一个Spring Boot项目;
选择我们需要的模块;
向导会联网创建Spring Boot项目; 默认生成的Spring Boot项目;
三、 配置文件
1、配置文件
SpringBoot使用一个全局的配置文件,配置文件名是固定的;
- application.properties
- application.yml
配置文件的作用:修改SpringBoot自动配置的默认值;SpringBoot在底层都给我们自动配置好;
YAML:以数据为中心,比json、xml等更适合做配置文件;
YAML:配置例子
server:
port: 8081
XML:
<server>
<port>8081</port>
</server>
2. YAML语法:
⑴基本语法
k:(空格)v 表示一对键值对(空格必须有);
以空格的缩进来控制层级关系;只要是左对齐的一列数据,都是同一个层级的
server: port: 8081 path: /hello
属性和值也是大小写敏感;
⑵ 值的写法
① 字面量:普通的值(数字,字符串,布尔)
k: v 字面直接来写;
字符串默认不用加上单引号或者双引号;
“”:双引号;不会转义字符串里面的特殊字符;特殊字符会作为本身想表示的意思
name: "zhangsan \n lisi":输出;zhangsan 换行 lisi
‘’:单引号;会转义特殊字符,特殊字符最终只是一个普通的字符串数据
name: ‘zhangsan \n lisi’:输出;zhangsan \n lisi
② 对象、Map(属性和值)(键值对):
k: v 在下一行来写对象的属性和值的关系;注意缩进
对象还是k: v的方式
friends:lastName: zhangsan age: 20
行内写法:
friends: {lastName: zhangsan,age: 18}
数组(List、Set):
用- 值表示数组中的一个元素pets: ‐ cat ‐ dog ‐ pig
行内写法
pets: [cat,dog,pig]
3. 配置文件值注入
⑴ 配置文件通过@ConfigurationProperties
注入值
① yaml配置文件值通过注解@ConfigurationProperties
的注入
项目结构如下:
application.yml
server:port: 8888person:lastName: zhangsanage: 18boss: falsebirthday: 2022/03/19maps: {k1: v1,k2: v2}lists:- lisi- zhaoliudog:name: 小狗age: 2
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.kejizhentan</groupId><artifactId>springboot-start</artifactId><version>1.0-SNAPSHOT</version><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><!--导入配置文件处理器,配置文件进行绑定就会有提示--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>
Person.java
/*** 将配置文件中配置的每一个属性的值,映射到这个组件中* @ConfigurationProperties:告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定;* prefix = "person":配置文件中哪个下面的所有属性进行一一映射** 只有这个组件是容器中的组件,才能容器提供的@ConfigurationProperties功能;* @ConfigurationProperties(prefix = "person")默认从全局配置文件中获取值;**/
@ConfigurationProperties(prefix = "person")
@Component
public class Person {private String lastName;private Integer age;private Boolean boss;private Date birthday;private Map<String,Object> maps;private List<Object> lists;private Dog dog;. . .
}
Dog.java
public class Dog {private String name;private Integer age;. . .
}
MainApplication.java
/*** 主程序类* @SpringBootApplication:这是一个SpringBoot应用*/
@SpringBootApplication
public class MainApplication {public static void main(String[] args) {SpringApplication.run(MainApplication.class,args);}
}
SpringBoot02ConfigApplicationTests.java
/*** SpringBoot单元测试;** 可以在测试期间很方便的类似编码一样进行自动注入等容器的功能**/
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBoot02ConfigApplicationTests {@AutowiredPerson person;@Testpublic void contextLoads() {System.out.println(person);}}
结果如下:
② properties配置文件值通过@ConfigurationProperties
的注入
项目结构如下:
application.properties
server.port=8888person.last-name=张三
person.age=18
person.birthday=2022/03/19
person.boss=false
person.maps.k1=v1
person.maps.k2=14
person.lists=a,b,c
person.dog.name=dog
person.dog.age=15
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.kejizhentan</groupId><artifactId>springboot-start</artifactId><version>1.0-SNAPSHOT</version><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><!--导入配置文件处理器,配置文件进行绑定就会有提示--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>
Person.java
/*** 将配置文件中配置的每一个属性的值,映射到这个组件中* @ConfigurationProperties:告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定;* prefix = "person":配置文件中哪个下面的所有属性进行一一映射** 只有这个组件是容器中的组件,才能容器提供的@ConfigurationProperties功能;* @ConfigurationProperties(prefix = "person")默认从全局配置文件中获取值;**/
@ConfigurationProperties(prefix = "person")
@Component
public class Person {private String lastName;private Integer age;private Boolean boss;private Date birthday;private Map<String,Object> maps;private List<Object> lists;private Dog dog;. . .
}
Dog.java
public class Dog {private String name;private Integer age;. . .
}
MainApplication.java
/*** 主程序类* @SpringBootApplication:这是一个SpringBoot应用*/
@SpringBootApplication
public class MainApplication {public static void main(String[] args) {SpringApplication.run(MainApplication.class,args);}
}
SpringBoot02ConfigApplicationTests.java
/*** SpringBoot单元测试;** 可以在测试期间很方便的类似编码一样进行自动注入等容器的功能**/
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBoot02ConfigApplicationTests {@AutowiredPerson person;@Testpublic void contextLoads() {System.out.println(person);}}
结果如下:
properties配置文件在idea中默认utf-8可能会乱码,需要做如下调整
⑵ 配置文件通过@Value注解注入值
因为propertties配置文件通过@Value注解注入值的方式和yaml一样,所以这里只拿yaml配置文件为例
项目结构如下:
application.yml
server:port: 8888person:lastName: zhangsanage: 18boss: falsebirthday: 2022/03/19maps: {k1: v1,k2: v2}lists:- lisi- zhaoliudog:name: 小狗age: 2
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.kejizhentan</groupId><artifactId>springboot-start</artifactId><version>1.0-SNAPSHOT</version><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><!--导入配置文件处理器,配置文件进行绑定就会有提示--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>
Person.java
@Component
public class Person {/*** <bean class="Person">* <property name="lastName" value="字面量/${key}从环境变量、配置文件中获取值/#{SpEL}"></property>* <bean/>*/@Value("${person.lastName}")private String lastName;@Value("#{11*11}")private Integer age;@Value("true")private Boolean boss;private Date birthday;private Map<String,Object> maps;private List<Object> lists;private Dog dog;. . .
}
Dog.java
public class Dog {private String name;private Integer age;. . .
}
MainApplication.java
/*** 主程序类* @SpringBootApplication:这是一个SpringBoot应用*/
@SpringBootApplication
public class MainApplication {public static void main(String[] args) {SpringApplication.run(MainApplication.class,args);}
}
SpringBoot02ConfigApplicationTests.java
/*** SpringBoot单元测试;** 可以在测试期间很方便的类似编码一样进行自动注入等容器的功能**/
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBoot02ConfigApplicationTests {@AutowiredPerson person;@Testpublic void contextLoads() {System.out.println(person);}}
结果如下:
⑶ @Value获取值和@ConfigurationProperties获取值比较
- 配置文件yml还是properties他们都能获取到值;
如果说,我们只是在某个业务逻辑中需要获取一下配置文件中的某项值,使用@Value;
如果说,我们专门编写了一个javaBean来和配置文件进行映射,我们就直接使用@ConfigurationProperties;- 松散语法属性名匹配规则(Relaxed binding)
– person.firstName:使用标准方式
– person.first-name:大写用-
– person.first_name:大写用_
– PERSON_FIRST_NAME: 推荐系统属性使用这种写法- @ConfigurationProperties支持JSR303进行配置文件值校验;
4. @PropertySource&@ImportResource&@Bean
⑴ @PropertySource:加载指定的配置文件();
项目结构如下:
主要的代码如下:
person.properties
person.last-name=zhangsan
person.age=18
person.birthday=2022/03/19
person.boss=false
person.maps.k1=v1
person.maps.k2=14
person.lists=a,b,c
person.dog.name=dog
person.dog.age=15
Person.java
/*** 将配置文件中配置的每一个属性的值,映射到这个组件中* @ConfigurationProperties:告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定;* prefix = "person":配置文件中哪个下面的所有属性进行一一映射** 只有这个组件是容器中的组件,才能容器提供的@ConfigurationProperties功能;* @ConfigurationProperties(prefix = "person")默认从全局配置文件中获取值;**/
@Component
@PropertySource(value = {"classpath:person.properties"})
@ConfigurationProperties(prefix = "person")
public class Person {private String lastName;private Integer age;private Boolean boss;private Date birthday;private Map<String,Object> maps;private List<Object> lists;private Dog dog;. . .
}
⑵ @ImportResource:导入Spring的配置文件,让配置文件里面的内容生效;
Spring Boot里面没有Spring的配置文件,我们自己编写的配置文件,也不能自动识别; 想让Spring的配置文件生效,加载进来;@ImportResource标注在一个配置类上
@ImportResource(locations = {“classpath:beans.xml”})
导入Spring的配置文件让其生效
详细代码如下:
项目结构如下:
beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans"><bean class="com.kejizhentan.service.HelloService" id="helloService"/>
</beans>
HelloService.java
public class HelloService {
}
DemoApplication.java
@SpringBootApplication
@ImportResource(locations = {"classpath:beans.xml"})
public class DemoApplication {public static void main(String[] args) {SpringApplication.run(DemoApplication.class, args);}}
DemoApplicationTests.java
/*** SpringBoot单元测试;** 可以在测试期间很方便的类似编码一样进行自动注入等容器的功能**/
@RunWith(SpringRunner.class)
@SpringBootTest
class DemoApplicationTests {@AutowiredApplicationContext ioc;@Testpublic void testHelloService(){boolean b = ioc.containsBean("helloService");System.out.println(b);}
}
结果如下:
⑶ @Bean
SpringBoot给容器中添加组件推荐使用全注解的方式
- 配置类@Configuration------>Spring配置文件
- 使用@Bean给容器中添加组件
项目结构如下:
详细代码如下:
HelloService.java
public class HelloService {
}
MyConfig.java
/*** @Configuration:指明当前类是一个配置类;就是来替代之前的Spring配置文件* 在配置文件中用<bean><bean/>标签添加组件**/
@Configuration
public class MyConfig {//将方法的返回值添加到容器中;容器中这个组件默认的id就是方法名@Beanpublic HelloService helloService02() {System.out.println("配置类@Bean给容器中添加组件了...");return new HelloService();}
}
DemoApplication.java
@SpringBootApplication
public class DemoApplication {public static void main(String[] args) {SpringApplication.run(DemoApplication.class, args);}}
DemoApplicationTests.java
/*** SpringBoot单元测试;** 可以在测试期间很方便的类似编码一样进行自动注入等容器的功能**/
@RunWith(SpringRunner.class)
@SpringBootTest
class DemoApplicationTests {@AutowiredApplicationContext ioc;@Testpublic void testHelloService(){boolean b = ioc.containsBean("helloService02");System.out.println(b);}
}
结果如下:
5.配置文件占位符
⑴ 随机数
${random.value}、${random.int}、${random.long} ${random.int(10)}、${random.int[1024,65536]}
⑵ 占位符获取之前配置的值,如果没有可以是用:指定默认值
person.last‐name=张三${random.uuid}
person.age=${random.int}
person.birth=2017/12/15
person.boss=false
person.maps.k1=v1
person.maps.k2=14
person.lists=a,b,c
person.dog.name=${person.hello:hello}_dog
person.dog.age=15
项目结构如下:
application.properties
server.port=8888person.last‐name=张三${random.uuid}
person.age=${random.int}
person.birth=2017/12/15
person.boss=false
person.maps.k1=v1
person.maps.k2=14
person.lists=a,b,c
person.dog.name=${person.hello:hello}_dog
person.dog.age=15
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.kejizhentan</groupId><artifactId>springboot-start</artifactId><version>1.0-SNAPSHOT</version><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><!--导入配置文件处理器,配置文件进行绑定就会有提示--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>
Person.java
/*** 将配置文件中配置的每一个属性的值,映射到这个组件中* @ConfigurationProperties:告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定;* prefix = "person":配置文件中哪个下面的所有属性进行一一映射** 只有这个组件是容器中的组件,才能容器提供的@ConfigurationProperties功能;* @ConfigurationProperties(prefix = "person")默认从全局配置文件中获取值;**/
@ConfigurationProperties(prefix = "person")
@Component
public class Person {private String lastName;private Integer age;private Boolean boss;private Date birthday;private Map<String,Object> maps;private List<Object> lists;private Dog dog;. . .
}
Dog.java
public class Dog {private String name;private Integer age;. . .
}
MainApplication.java
/*** 主程序类* @SpringBootApplication:这是一个SpringBoot应用*/
@SpringBootApplication
public class MainApplication {public static void main(String[] args) {SpringApplication.run(MainApplication.class,args);}
}
SpringBoot02ConfigApplicationTests.java
/*** SpringBoot单元测试;** 可以在测试期间很方便的类似编码一样进行自动注入等容器的功能**/
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBoot02ConfigApplicationTests {@AutowiredPerson person;@Testpublic void contextLoads() {System.out.println(person);}}
结果如下:
6.Profile
Profile是Spring对不同环境提供不同配置功能的支持,可以通过激活、指定参数等方式快速切换环境
⑴ 多profile文件形式:
格式:application-{profile}.properties/yml:
例如:application-dev.properties、application-prod.properties
默认使用application.properties的配置;
⑵ yml支持多profile文档块模式:
格式如下:
server:port: 8081
spring:profiles:active: prod #使prod环境中的文档快生效---server:port: 8083
spring:profiles: dev---
server:port: 8084
spring:profiles: prod #指定属于哪个环境
⑶ 激活指定profile
在配置文件中指定 spring.profiles.active=dev
启动jar包的时候使用命令行的方式: java -jar spring-boot-02-config-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev
可以直接在测试的时候,配置传入命令行参数
虚拟机参数; -Dspring.profiles.active=dev
⑷ 配置文件加载位置
spring boot 启动会扫描以下位置的application.properties或者application.yml文件作为Spring boot的默认配置文件
– file:./config/
– file:./
– classpath:/config/
– classpath:/
– 以上是按照优先级从高到低的顺序,所有位置的文件都会被加载,高优先级配置内容会覆盖低优先级配置内容。
SpringBoot会从这四个位置全部加载主配置文件;互补配置;
我们还可以通过spring.config.location
来改变默认的配置文件位置,这个方式只适用于项目打包好以后,我们可以使用命令行参数的形式,启动项目的时候来指定配置文件的新位置;指定配置文件和默 认加载的这些配置文件共同起作用形成互补配置;
java -jar spring-boot-02-config-02-0.0.1-SNAPSHOT.jar --spring.config.location=G:/application.properties
⑸ 外部配置加载顺序
SpringBoot也可以从以下位置加载配置; 优先级从高到低;高优先级的配置覆盖低优先级的配置,所有的配置会 形成互补配置
- 命令行参数 所有的配置都可以在命令行上进行指定
java -jar spring-boot-02-config-02-0.0.1-SNAPSHOT.jar --server.port=8087 --server.context-path=/abc
多个配置用空格分开; --配置项=值 - 来自java:comp/env的JNDI属性
- Java系统属性(System.getProperties())
- 操作系统环境变量
- .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指定的默认属性
参考官方文档
四、自动配置原理
配置文件能配置的属性参照
1. 自动配置底层原理:
⑴ SpringBoot启动的时候加载主配置类,开启了自动配置功能 @EnableAutoConfiguration
⑵ @EnableAutoConfiguration
作用:
利用
EnableAutoConfigurationImportSelector
给容器中导入一些组件可以查看selectImports()方法的内容;
List configurations = getCandidateConfigurations(annotationMetadata, attributes);获取候选的配置
SpringFactoriesLoader.loadFactoryNames()
扫描所有jar包类路径下 META‐INF/spring.factories
把扫描到的这些文件的内容包装成properties对象
从properties中获取到EnableAutoConfiguration.class类(类名)对应的值,然后把他们添加在容器 中
将 类路径下 META-INF/spring.factories 里面配置的所有EnableAutoConfiguration的值加入到了容器中;# Auto Configure org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\ org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\ org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\ org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\ org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\ org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration,\ org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration,\ org.springframework.boot.autoconfigure.context.LifecycleAutoConfiguration,\ org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration,\ org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration,\ org.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfiguration,\ org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration,\ org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration,\ org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveDataAutoConfiguration,\ org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.cassandra.CassandraRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration,\ org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveDataAutoConfiguration,\ org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.couchbase.CouchbaseRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration,\ org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.elasticsearch.ReactiveElasticsearchRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.elasticsearch.ReactiveElasticsearchRestClientAutoConfiguration,\ org.springframework.boot.autoconfigure.data.jdbc.JdbcRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.ldap.LdapRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration,\ org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration,\ org.springframework.boot.autoconfigure.data.mongo.MongoReactiveRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration,\ org.springframework.boot.autoconfigure.data.neo4j.Neo4jRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.r2dbc.R2dbcDataAutoConfiguration,\ org.springframework.boot.autoconfigure.data.r2dbc.R2dbcRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.r2dbc.R2dbcTransactionManagerAutoConfiguration,\ org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,\ org.springframework.boot.autoconfigure.data.redis.RedisReactiveAutoConfiguration,\ org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration,\ org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration,\ org.springframework.boot.autoconfigure.elasticsearch.ElasticsearchRestClientAutoConfiguration,\ org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration,\ org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration,\ org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration,\ org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration,\ org.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfiguration,\ org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration,\ org.springframework.boot.autoconfigure.hazelcast.HazelcastAutoConfiguration,\ org.springframework.boot.autoconfigure.hazelcast.HazelcastJpaDependencyAutoConfiguration,\ org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration,\ org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration,\ org.springframework.boot.autoconfigure.influx.InfluxDbAutoConfiguration,\ org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration,\ org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration,\ org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration,\ org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\ org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration,\ org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration,\ org.springframework.boot.autoconfigure.jdbc.XADataSourceAutoConfiguration,\ org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration,\ org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration,\ org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration,\ org.springframework.boot.autoconfigure.jms.JndiConnectionFactoryAutoConfiguration,\ org.springframework.boot.autoconfigure.jms.activemq.ActiveMQAutoConfiguration,\ org.springframework.boot.autoconfigure.jms.artemis.ArtemisAutoConfiguration,\ org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration,\ org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration,\ org.springframework.boot.autoconfigure.jsonb.JsonbAutoConfiguration,\ org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration,\ org.springframework.boot.autoconfigure.availability.ApplicationAvailabilityAutoConfiguration,\ org.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapAutoConfiguration,\ org.springframework.boot.autoconfigure.ldap.LdapAutoConfiguration,\ org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration,\ org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration,\ org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration,\ org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration,\ org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,\ org.springframework.boot.autoconfigure.mongo.MongoReactiveAutoConfiguration,\ org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration,\ org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,\ org.springframework.boot.autoconfigure.quartz.QuartzAutoConfiguration,\ org.springframework.boot.autoconfigure.r2dbc.R2dbcAutoConfiguration,\ org.springframework.boot.autoconfigure.rsocket.RSocketMessagingAutoConfiguration,\ org.springframework.boot.autoconfigure.rsocket.RSocketRequesterAutoConfiguration,\ org.springframework.boot.autoconfigure.rsocket.RSocketServerAutoConfiguration,\ org.springframework.boot.autoconfigure.rsocket.RSocketStrategiesAutoConfiguration,\ org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration,\ org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration,\ org.springframework.boot.autoconfigure.security.servlet.SecurityFilterAutoConfiguration,\ org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration,\ org.springframework.boot.autoconfigure.security.reactive.ReactiveUserDetailsServiceAutoConfiguration,\ org.springframework.boot.autoconfigure.security.rsocket.RSocketSecurityAutoConfiguration,\ org.springframework.boot.autoconfigure.security.saml2.Saml2RelyingPartyAutoConfiguration,\ org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration,\ org.springframework.boot.autoconfigure.session.SessionAutoConfiguration,\ org.springframework.boot.autoconfigure.security.oauth2.client.servlet.OAuth2ClientAutoConfiguration,\ org.springframework.boot.autoconfigure.security.oauth2.client.reactive.ReactiveOAuth2ClientAutoConfiguration,\ org.springframework.boot.autoconfigure.security.oauth2.resource.servlet.OAuth2ResourceServerAutoConfiguration,\ org.springframework.boot.autoconfigure.security.oauth2.resource.reactive.ReactiveOAuth2ResourceServerAutoConfiguration,\ org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration,\ org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration,\ org.springframework.boot.autoconfigure.task.TaskSchedulingAutoConfiguration,\ org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration,\ org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration,\ org.springframework.boot.autoconfigure.transaction.jta.JtaAutoConfiguration,\ org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration,\ org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration,\ org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration,\ org.springframework.boot.autoconfigure.web.reactive.HttpHandlerAutoConfiguration,\ org.springframework.boot.autoconfigure.web.reactive.ReactiveWebServerFactoryAutoConfiguration,\ org.springframework.boot.autoconfigure.web.reactive.WebFluxAutoConfiguration,\ org.springframework.boot.autoconfigure.web.reactive.error.ErrorWebFluxAutoConfiguration,\ org.springframework.boot.autoconfigure.web.reactive.function.client.ClientHttpConnectorAutoConfiguration,\ org.springframework.boot.autoconfigure.web.reactive.function.client.WebClientAutoConfiguration,\ org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration,\ org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration,\ org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration,\ org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration,\ org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration,\ org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration,\ org.springframework.boot.autoconfigure.websocket.reactive.WebSocketReactiveAutoConfiguration,\ org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration,\ org.springframework.boot.autoconfigure.websocket.servlet.WebSocketMessagingAutoConfiguration,\ org.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration,\ org.springframework.boot.autoconfigure.webservices.client.WebServiceTemplateAutoConfiguration
每一个这样的 xxxAutoConfiguration类都是容器中的一个组件,都加入到容器中;用他们来做自动配置;
⑶ 每一个自动配置类进行自动配置功能
2. 以HttpEncodingAutoConfiguration(Http编码自动配置)为例解释自动配置原理;
@Configuration(proxyBeanMethods = false
)//表示这是一个配置类,以前编写的配置文件一样,也可以给容器中添加组件
@EnableConfigurationProperties({ServerProperties.class})//启动指定类的EnableConfigurationProperties功能;将配置文件中对应的值和ServerProperties绑定起来;并把 ServerProperties加入到ioc容器中
@ConditionalOnWebApplication(type = Type.SERVLET
)//Spring底层@Conditional注解(Spring注解版),根据不同的条件,如果 满足指定的条件,整个配置类里面的配置就会生效; 判断当前应用是否是web应用,如果是,当前配置类生效
@ConditionalOnClass({CharacterEncodingFilter.class})//判断当前项目有没有这个类 CharacterEncodingFilter;SpringMVC中进行乱码解决的过滤器;
@ConditionalOnProperty(prefix = "server.servlet.encoding",value = {"enabled"},matchIfMissing = true
)//判断配置文件中是否存在某个配置 server.servlet.encoding.enabled;如果不存在,判断也是成立的 //即使我们配置文件中不配置
public class HttpEncodingAutoConfiguration {//他已经和SpringBoot的配置文件映射了private final Encoding properties;//只有一个有参构造器的情况下,参数的值就会从容器中拿public HttpEncodingAutoConfiguration(ServerProperties properties) {this.properties = properties.getServlet().getEncoding();}@Bean//给容器中添加一个组件,这个组件的某些值需要从properties中获取@ConditionalOnMissingBean//判断容器没有这个组件?public CharacterEncodingFilter characterEncodingFilter() {CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();filter.setEncoding(this.properties.getCharset().name());filter.setForceRequestEncoding(this.properties.shouldForce(org.springframework.boot.web.servlet.server.Encoding.Type.REQUEST));filter.setForceResponseEncoding(this.properties.shouldForce(org.springframework.boot.web.servlet.server.Encoding.Type.RESPONSE));return filter;}@Beanpublic HttpEncodingAutoConfiguration.LocaleCharsetMappingsCustomizer localeCharsetMappingsCustomizer() {return new HttpEncodingAutoConfiguration.LocaleCharsetMappingsCustomizer(this.properties);}static class LocaleCharsetMappingsCustomizer implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory>, Ordered {private final Encoding properties;LocaleCharsetMappingsCustomizer(Encoding properties) {this.properties = properties;}public void customize(ConfigurableServletWebServerFactory factory) {if (this.properties.getMapping() != null) {factory.setLocaleCharsetMappings(this.properties.getMapping());}}public int getOrder() {return 0;}}
}
上面的代码总结一句话就是:根据当前不同的条件判断,决定这个配置类是否生效? 一但这个配置类生效;这个配置类就会给容器中添加各种组件;这些组件的属性是从对应的properties类中获取 的,这些类里面的每一个属性又是和配置文件绑定的
所有在配置文件中能配置的属性都是在xxxxProperties类中封装者‘;配置文件能配置什么就可以参照某个功 能对应的这个属性类
@ConfigurationProperties(prefix = "server",ignoreUnknownFields = true
)//从配置文件中获取指定的值和bean的属 性进行绑定
public class ServerProperties {private Integer port;private InetAddress address;
3. @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存在指定项 |
自动配置类必须在一定的条件下才能生效;
我们怎么知道哪些自动配置类生效?
我们可以通过启用 debug=true属性;来让控制台打印自动配置报告,这样我们就可以很方便的知道哪些自动配置 类生效;
五、Spring Boot与日志
市场上存在非常多的日志框架。JUL(java.util.logging),JCL(Apache Commons Logging),Log4j,Log4j2,Logback、SLF4j、jboss-logging等。Spring Boot在框架内容部使用JCL,spring-boot-starter-logging采用了slf4j+logback的形式,Spring Boot也能自动适配(jul、log4j2、logback) 并简化配置
左边选一个门面(抽象层)、右边来选一个实现;
日志门面: SLF4J; 日志实现:Logback;
SpringBoot:底层是Spring框架,Spring框架默认是用JCL;‘ SpringBoot选用 SLF4j和logback;
1. SLF4j使用
⑴ 如何在系统中使用SLF4j
以后开发的时候,日志记录方法的调用,不应该来直接调用日志的实现类,而是调用日志抽象层里面的方法; 给系统里面导入slf4j的jar和 logback的实现jar
每一个日志的实现框架都有自己的配置文件。使用slf4j以后,配置文件还是做成日志实现框架自己本身的配置文 件;
⑵ 遗留问题
application——自己的项目(slf4j+logback): Spring(commons-logging)、Hibernate(jboss-logging)、MyBatis、xxxx 统一日志记录,即使是别的框架和我一起统一使用slf4j进行输出?
如何让系统中所有的日志都统一到slf4j;
1、将系统中其他日志框架先排除出去;
2、用中间包来替换原有的日志框架;
3、我们导入slf4j其他的实现
六、Spring Boot与Web开发
1. SpringBoot的web项目对静态资源的映射规则
⑴ 所有 /webjars/** ,都去 classpath:/META-INF/resources/webjars/ 找资源;
webjars:以jar包的方式引入静态资源;
流行的流行的 WebJars 如下:
https://www.webjars.org/
<!--pom文件中引入Airbrake-JS的webjars包-->
<dependency><groupId>org.webjars</groupId><artifactId>airbrake-js</artifactId><version>0.3</version>
</dependency>
如下图:
访问webjars资源
http://localhost:8081/webjars/airbrake-js/0.3/airbrake.js
⑵ “/**” 访问当前项目的任何资源,都去(静态资源的文件夹)找映射
静态资源的文件夹:
"classpath:/META‐INF/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/"
"/":当前项目的根路径
底层原理如下图:
springboot访问当前项目的任何资源时如果没有做任何的处理,默认去静态资源的文件夹中找相应的资源股
localhost:8080/abc === 去静态资源文件夹里面找abc
例如:
⑶ 欢迎页; 静态资源文件夹下的所有index.html页面;被"/**"映射;
底部原理如下:
例如:
localhost:8081/ 找index页面
可以在配置文件中修改默认的静态文件夹名称,一般都不这么做,慎用!!!
spring.resources.static-locations=classpath:/hello/,classpath:/kejizhentan
2. Thymeleaf模板引擎
点击下载Thymeleaf模板开发手册
常见的模板引擎如下:
JSP、Velocity、Freemarker、Thymeleaf…
SpringBoot推荐的Thymeleaf; 语法更简单,功能更强大;
⑴ 引入thymeleaf;
<!--引入Thymeleaf模板引擎所需要的依赖-->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
切换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>
⑵ Thymeleaf使用
@ConfigurationProperties(prefix = "spring.thymeleaf"
)
public class ThymeleafProperties {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";private String mode = "HTML";private Charset encoding;private boolean cache;private Integer templateResolverOrder;private String[] viewNames;private String[] excludedViewNames;private boolean enableSpringElCompiler;private boolean renderHiddenMarkersBeforeCheckboxes;private boolean enabled;private final ThymeleafProperties.Servlet servlet;private final ThymeleafProperties.Reactive reactive;public ThymeleafProperties() {this.encoding = DEFAULT_ENCODING;this.cache = true;this.renderHiddenMarkersBeforeCheckboxes = false;this.enabled = true;this.servlet = new ThymeleafProperties.Servlet();this.reactive = new ThymeleafProperties.Reactive();}
只要我们把HTML页面放在classpath:/templates/,thymeleaf就能自动渲染;
开发步骤如下:
导入thymeleaf的名称空间(用于校验thymeleaf语法格式)
<html lang="en" xmlns:th="http://www.thymeleaf.org">
使用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里面的文本内容设置为${hello}中的内容--><div th:text="${hello}">这是显示欢迎信息</div> </body> </html>
详细代码如下:
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.kejizhentan</groupId><artifactId>springboot-web-project</artifactId><version>0.0.1-SNAPSHOT</version><name>springboot-web-project</name><description>com.kejizhentan.springbootwebproject</description><properties><java.version>1.8</java.version><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><spring-boot.version>2.3.7.RELEASE</spring-boot.version><thymeleaf.version>3.0.9.RELEASE</thymeleaf.version><!-- 布局功能的支持程序 thymeleaf3主程序 layout2以上版本 --><!-- thymeleaf2 layout1--><thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version></properties><dependencies><!--引入web模块--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--引入Thymeleaf模板引擎所需要的依赖--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope><exclusions><exclusion><groupId>org.junit.vintage</groupId><artifactId>junit-vintage-engine</artifactId></exclusion></exclusions></dependency></dependencies><dependencyManagement><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-dependencies</artifactId><version>${spring-boot.version}</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement><build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.8.1</version><configuration><source>1.8</source><target>1.8</target><encoding>UTF-8</encoding></configuration></plugin><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><version>2.3.7.RELEASE</version><configuration><mainClass>com.kejizhentan.springbootwebproject.SpringbootWebProjectApplication</mainClass></configuration><executions><execution><id>repackage</id><goals><goal>repackage</goal></goals></execution></executions></plugin></plugins></build>
</project>
application.properties
# 应用服务 WEB 访问端口
server.port=8081
success.html
<!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里面的文本内容设置为${hello}中的内容--><div th:text="${hello}">这是显示欢迎信息</div>
</body>
</html>
SpringbootWebProjectApplication.java
@SpringBootApplication
public class SpringbootWebProjectApplication {public static void main(String[] args) {SpringApplication.run(SpringbootWebProjectApplication.class, args);}
}
HelloController.java
@Controller
public class HelloController {//模拟从数据库中查出一些数据在页面上展示@RequestMapping("/success")public String sayHello(Map<String,String> map){map.put("hello","你好");//classpath:/templates/success.htmlreturn "success";}
}
效果如下:
⑶ Thymeleaf语法规则
1) th:text;改变当前元素里面的文本内容;
th:任意html属性;来替换原生属性的值
2)Thymeleaf表达式
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.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: _
案例代码如下:
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.kejizhentan</groupId><artifactId>springboot-web-project</artifactId><version>0.0.1-SNAPSHOT</version><name>springboot-web-project</name><description>com.kejizhentan.springbootwebproject</description><properties><java.version>1.8</java.version><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><spring-boot.version>2.3.7.RELEASE</spring-boot.version><thymeleaf.version>3.0.9.RELEASE</thymeleaf.version><!-- 布局功能的支持程序 thymeleaf3主程序 layout2以上版本 --><!-- thymeleaf2 layout1--><thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version></properties><dependencies><!--引入web模块--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--引入Thymeleaf模板引擎所需要的依赖--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope><exclusions><exclusion><groupId>org.junit.vintage</groupId><artifactId>junit-vintage-engine</artifactId></exclusion></exclusions></dependency></dependencies><dependencyManagement><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-dependencies</artifactId><version>${spring-boot.version}</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement><build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.8.1</version><configuration><source>1.8</source><target>1.8</target><encoding>UTF-8</encoding></configuration></plugin><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><version>2.3.7.RELEASE</version><configuration><mainClass>com.kejizhentan.springbootwebproject.SpringbootWebProjectApplication</mainClass></configuration><executions><execution><id>repackage</id><goals><goal>repackage</goal></goals></execution></executions></plugin></plugins></build>
</project>
application.properties
# 应用服务 WEB 访问端口
server.port=8081
success.html
<!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里面的文本内容设置为${hello}中的内容--><div th:text="${hello}">这是显示欢迎信息</div><hr><!--转义特殊字符--><div th:text="${hello}"></div><!--不转义特殊字符--><div th:utext="${hello}"></div><hr><!--th:each 每次遍历都会生成当前这个标签,也就是会生成三个<h4>标签--><h4 th:text="${user}" th:each="user:${users}"></h4><hr><h4><span th:each="user:${users}"> [[${user}]]</span></h4></body>
</html>
SpringbootWebProjectApplication.java
@SpringBootApplication
public class SpringbootWebProjectApplication {public static void main(String[] args) {SpringApplication.run(SpringbootWebProjectApplication.class, args);}
}
HelloController.java
@Controller
public class HelloController {//模拟从数据库中查出一些数据在页面上展示@RequestMapping("/success")public String sayHello(Map<String,Object> map){List<String> users = new ArrayList<>();map.put("hello","<h1>你好</h1>");map.put("users", Arrays.asList("zhangsan","lisi","wangwu"));//classpath:/templates/success.htmlreturn "success";}
}
效果如下:
3. SpringMVC自动配置
详细介绍请点击官方链接介绍:
https://docs.spring.io/spring-boot/docs/1.5.10.RELEASE/reference/htmlsingle/#boot-features-developing- web-applications
⑴ Spring MVC官方介绍:
Spring Boot 自动配置好了SpringMVC
以下是SpringBoot对SpringMVC的默认配置:(WebMvcAutoConfiguration)
Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans.
1.自动配置了ViewResolver(视图解析器:根据方法的返回值得到视图对象(View),视图对象决定如何 渲染(转发?重定向?))
2.ContentNegotiatingViewResolver:组合所有的视图解析器的;
3. 如何定制:我们可以自己给容器中添加一个视图解析器;ContentNegotiatingViewResolver会自动的将其组合进来;
springboot自动配置SpringMVC相关源码如下:
自己给容器中添加一个自定义视图解析器,并让ContentNegotiatingViewResolver自动的将其组合进来的相关代码:Support for serving static resources, including support for WebJars (see below).静态资源文件夹路 径和webjars
Static index.html support. 静态首页访问
Custom Favicon support (see below). favicon.ico
自动注册了 of
Converter
,GenericConverter
,Formatter beans
.
1.Converter
转换器: public String hello(User user):类型转换使用Converter
2. Formatter 格式化器: 2017/12/17==>Date;自己添加的格式化器转换器,我们只需要放在容器中即可
Support for HttpMessageConverters (see below).
1 .HttpMessageConverter
:SpringMVC用来转换Http请求和响应的;User==>Json;
2 .HttpMessageConverters
是从容器中确定;获取所有的HttpMessageConverter自己给容器中添加HttpMessageConverter,只需要将自己的组件注册容器中 (@Bean,@Component)
Automatic registration of MessageCodesResolver (see below).定义错误代码生成规则
Automatic use of a ConfigurableWebBindingInitializer bean (see below).
我们可以配置一个ConfigurableWebBindingInitializer来替换默认的;(添加到容器)ConfigurableWebBindingInitializer 的作用是初始化WebDataBinder(web数据绑定器),可以将请求数据转换成javaBean对象
web的所有自动配置的场景都在这个包下:
org.springframework.boot.autoconfigure.web.servlet:
⑵ 扩展SpringMVC
以前ssm架构时候springMVC文件中的配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://www.springframework.org/schema/beans"><mvc:view-controller view-name="success" path="/hello"/><mvc:interceptors><mvc:interceptor><mvc:mapping path="/hello"/><bean/></mvc:interceptor></mvc:interceptors><mvc:default-servlet-handler/>
</bean
springBoot不用编写springMVC配置文件,只需要编写一个配置类(@Configuration),是WebMvcConfigurerAdapter类型不能标注@EnableWebMvc;
既保留了所有的自动配置,也能用我们扩展的配置;
//使用WebMvcConfigurerAdapter可以来扩展SpringMVC的功能
@Configuration
public class MyMVCConfig extends WebMvcConfigurerAdapter {@Overridepublic void addViewControllers(ViewControllerRegistry registry) {super.addViewControllers(registry);// 浏览器发送 /kejizhentan 请求来到 successregistry.addViewController("/kejizhentan").setViewName("success"); }
}
项目结构如下:
MyMVCConfig.java
//使用WebMvcConfigurerAdapter可以来扩展SpringMVC的功能
@Configuration
public class MyMVCConfig extends WebMvcConfigurerAdapter {@Overridepublic void addViewControllers(ViewControllerRegistry registry) {super.addViewControllers(registry);// 浏览器发送 /kejizhentan 请求来到 successregistry.addViewController("/kejizhentan").setViewName("success"); }
}
HelloController.java
@Controller
public class HelloController {}
SpringbootWebProjectApplication.java
@SpringBootApplication
public class SpringbootWebProjectApplication {public static void main(String[] args) {SpringApplication.run(SpringbootWebProjectApplication.class, args);}
}
success.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body><h1>执行成功</h1>
</body>
</html>
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.kejizhentan</groupId><artifactId>springboot-web-project</artifactId><version>0.0.1-SNAPSHOT</version><name>springboot-web-project</name><description>com.kejizhentan.springbootwebproject</description><properties><java.version>1.8</java.version><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><spring-boot.version>2.3.7.RELEASE</spring-boot.version><thymeleaf.version>3.0.9.RELEASE</thymeleaf.version><!-- 布局功能的支持程序 thymeleaf3主程序 layout2以上版本 --><!-- thymeleaf2 layout1--><thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version></properties><dependencies><!--引入web模块--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--引入Thymeleaf模板引擎所需要的依赖--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope><exclusions><exclusion><groupId>org.junit.vintage</groupId><artifactId>junit-vintage-engine</artifactId></exclusion></exclusions></dependency></dependencies><dependencyManagement><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-dependencies</artifactId><version>${spring-boot.version}</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement><build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.8.1</version><configuration><source>1.8</source><target>1.8</target><encoding>UTF-8</encoding></configuration></plugin><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><version>2.3.7.RELEASE</version><configuration><mainClass>com.kejizhentan.springbootwebproject.SpringbootWebProjectApplication</mainClass></configuration><executions><execution><id>repackage</id><goals><goal>repackage</goal></goals></execution></executions></plugin></plugins></build>
</project>
效果如下:
扩展SpringMVC原理分析:
1)、WebMvcAutoConfiguration是SpringMVC的自动配置类
2)、在做其他自动配置时会导入;@Import(EnableWebMvcConfiguration.class)
3)、容器中所有的WebMvcConfigurer都会一起起作用;
4)、我们的配置类也会被调用;
效果:SpringMVC的自动配置和我们的扩展配置都会起作用;
⑶ 全面接管SpringMVC;
SpringBoot对SpringMVC的自动配置不需要了,所有都是我们自己配置;所有的SpringMVC的自动配置都失效了
我们需要在配置类中添加@EnableWebMvc即可;
//全面接管SpringMVC,使所有的SpringMVC的自动配置都失效了
@EnableWebMvc
//使用WebMvcConfigurerAdapter可以来扩展SpringMVC的功能
@Configuration
public class MyMVCConfig extends WebMvcConfigurerAdapter {@Overridepublic void addViewControllers(ViewControllerRegistry registry) {super.addViewControllers(registry);// 浏览器发送 /kejizhentan 请求来到 successregistry.addViewController("/kejizhentan").setViewName("success"); }
}
原理: 为什么@EnableWebMvc自动配置就失效了;
4. 如何修改springBoot的默认配置
模式:
1)、SpringBoot在自动配置很多组件的时候,先看容器中有没有用户自己配置的(@Bean、@Component)如 果有就用用户配置的,如果没有,才自动配置;如果有些组件可以有多个(ViewResolver)将用户配置的和自己默 认的组合起来;
2)、在SpringBoot中会有非常多的xxxConfigurer帮助我们进行扩展配置
3)、在SpringBoot中会有很多的xxxCustomizer帮助我们进行定制配置
5. SpringBoot实现RestfulCRUD的开发介绍
⑴ 默认访问首页
默认是访问静态资源文件夹静态资源的文件夹
“classpath:/META‐INF/resources/”,
“classpath:/resources/”,
“classpath:/static/”,
“classpath:/public/” 中的index.html文件
⑵ 设置系统默认访问templates文件下index.html页面的方式
① 通过写Controller来设置系统的默认访问的页面index.html
@Controller
public class HelloController {@RequestMapping({"/","/index.html"})public String index(){return "index";}
}
② 通过使用WebMvcConfigurerAdapter可以来扩展SpringMVC的功能来设置默认访问的页面
@Configuration
public class MyMVCConfig extends WebMvcConfigurerAdapter {@Overridepublic void addViewControllers(ViewControllerRegistry registry) {super.addViewControllers(registry);// 浏览器发送 / 请求来到 indexregistry.addViewController("/").setViewName("index"); }
}
③ 通过重新配置WebMvcConfigurerAdapter方式来设置系统默认访问的页面
//使用WebMvcConfigurerAdapter可以来扩展SpringMVC的功能
@Configuration
public class MyMVCConfig extends WebMvcConfigurerAdapter {//所有的WebMvcConfigurerAdapter组件都会一起起作用@Bean //将组件注册在容器public WebMvcConfigurerAdapter webMvcConfigurerAdapter(){WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() {@Overridepublic void addViewControllers(ViewControllerRegistry registry) {registry.addViewController("/").setViewName("index");registry.addViewController("/index.html").setViewName("index");registry.addViewController("/main.html").setViewName("index");}};return adapter;}
}
⑶ 国际化
① 编写国际化配置文件;
② 使用ResourceBundleMessageSource管理国际化资源文件
③ 在页面使用fmt:message取出国际化内容
步骤:
1)、编写国际化配置文件,抽取页面需要显示的国际化消息
效果:根据浏览器语言设置的信息切换了国际化;
2)、SpringBoot自动配置好了管理国际化资源文件的组件;
3)、去页面获取国际化的值;
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"><meta name="description" content=""><meta name="author" content=""><title>Signin Template for Bootstrap</title><!-- Bootstrap core CSS --><!--使用webjars引入资源文件的好处:无论项目路径如何修改,仍然可以正常访问静态资源--><link href="asserts/css/bootstrap.min.css" th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="stylesheet"><!-- Custom styles for this template --><link href="asserts/css/signin.css" th:href="@{/asserts/css/signin.css}" rel="stylesheet"></head><body class="text-center"><form class="form-signin" action="dashboard.html"><img class="mb-4" th:src="@{/asserts/img/bootstrap-solid.svg}" src="asserts/img/bootstrap-solid.svg" alt="" width="72" height="72"><!--通过国际化语言的配置文件来替换页面中的值--><h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign in</h1><label class="sr-only" th:text="#{login.username}">Username</label><input type="text" class="form-control" placeholder="Username" th:placeholder="#{login.username}" required="" autofocus=""><label class="sr-only" th:text="#{login.password}">Password</label><input type="password" class="form-control" placeholder="Password" th:placeholder="#{login.password}" required=""><div class="checkbox mb-3"><label><!--注意checkbox勾选框通过国际化语言替换页面值的方式--><input type="checkbox" value="remember-me"> [[#{login.remember}]]</label></div><button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.btn}">Sign in</button><p class="mt-5 mb-3 text-muted">© 2017-2018</p><a class="btn btn-sm">中文</a><a class="btn btn-sm">English</a></form></body>
</html>
springMVC实现国际化的原理:
国际化Local(区域信息对象),LocalResolver(获取区域信息对象)
4)、点击链接切换国际化
<a class="btn btn-sm" th:href="@{/index.html(l='zh_CN')}">中文</a>
<a class="btn btn-sm" th:href="@{/index.html(l='en_US')}">English</a>
/*** @Auther: kejizhentan* @Date 2022/3/27 23:00* @Description: 自定义区域解析器,可以在连接上携带区域信息*/
public class MyLocaleResolver implements LocaleResolver {@Overridepublic Locale resolveLocale(HttpServletRequest httpServletRequest) {//获取请求头的l参数的值String l = httpServletRequest.getParameter("l");//设置区域信息对象的值是系统默认的区域信息的值Locale locale = Locale.getDefault();if (!StringUtils.isEmpty(l)) {//将请求参数的值一分为二,一个是语言代码,一个是国家代码String[] split = l.split("_");locale = new Locale(split[0], split[1]);}return locale;}@Overridepublic void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {}
}
//将自定义的区域解析器注入到容器中@Beanpublic LocaleResolver localeResolver(){return new MyLocaleResolver();}
效果如下:
⑷ 登录功能的实现
开发期间模板引擎页面修改以后,要实时生效的方法:
禁用模板引擎的缓存
#禁用Thymeleaf缓存 spring.thymeleaf.cache=false
页面修改完成以后ctrl+f9:重新编译;
登陆错误消息的显示
<!--判断错误提示内容是否为空,如果不为空显示提示的内容,注意其中thymeleaf的内置对象strings-->
<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
① 拦截器进行登陆检查
定义拦截器
/*** 登陆检查拦截器,*/
public class LoginHandlerInterceptor implements HandlerInterceptor {//目标方法执行之前@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {Object user = request.getSession().getAttribute("loginUser");if(user == null){//未登陆,返回登陆页面request.setAttribute("msg","没有权限请先登陆");request.getRequestDispatcher("/index.html").forward(request,response);return false;}else{//已登陆,放行请求return true;}}
}
注册拦截器
//使用WebMvcConfigurerAdapter可以来扩展SpringMVC的功能
@Configuration
public class MyMVCConfig extends WebMvcConfigurerAdapter {//所有的WebMvcConfigurerAdapter组件都会一起起作用@Bean //将组件注册在容器public WebMvcConfigurerAdapter webMvcConfigurerAdapter(){WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() {@Overridepublic void addViewControllers(ViewControllerRegistry registry) {registry.addViewController("/").setViewName("login");registry.addViewController("/index.html").setViewName("login");//加个视图映射,当发送/main.html请求的时候会跳转到dashboard页面registry.addViewController("/main.html").setViewName("dashboard");}//注册拦截器@Overridepublic void addInterceptors(InterceptorRegistry registry) {//将自定义的拦截器注册到容器中,设置拦截所有的请求,并将"/index.html","/","/user/login"请求都放开//SpringBoot1.X已经做好了静态资源映射 静态资源; *.css , *.js都不需要配置了//如果SpringBoot2.X就要放开静态资源的拦截registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**").excludePathPatterns("/index.html","/","/user/login","/asserts/css/**","/asserts/img/**","/asserts/js/**","/webjars/**");;}};return adapter;}//将自定义的区域解析器注入到容器中@Beanpublic LocaleResolver localeResolver(){return new MyLocaleResolver();}
}
② 用户登录的核心代码
项目结构如下:
login.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"><meta name="description" content=""><meta name="author" content=""><title>Signin Template for Bootstrap</title><!-- Bootstrap core CSS --><!--使用webjars引入资源文件的好处:无论项目路径如何修改,仍然可以正常访问静态资源--><link href="asserts/css/bootstrap.min.css" th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="stylesheet"><!-- Custom styles for this template --><link href="asserts/css/signin.css" th:href="@{/asserts/css/signin.css}" rel="stylesheet"></head><body class="text-center"><form class="form-signin" action="dashboard.html" th:action="@{/user/login}" method="post"><img class="mb-4" th:src="@{/asserts/img/bootstrap-solid.svg}" src="asserts/img/bootstrap-solid.svg" alt="" width="72" height="72"><h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign in</h1><!--判断错误提示内容是否为空,如果不为空显示提示的内容,注意其中thymeleaf的内置对象strings--><p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p><label class="sr-only" th:text="#{login.username}">Username</label><input type="text" class="form-control" name="username" placeholder="Username" th:placeholder="#{login.username}" required="" autofocus=""><label class="sr-only" th:text="#{login.password}">Password</label><input type="password" class="form-control" placeholder="Password" name="password" th:placeholder="#{login.password}" required=""><div class="checkbox mb-3"><label><input type="checkbox" value="remember-me"> [[#{login.remember}]]</label></div><button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.btn}">Sign in</button><p class="mt-5 mb-3 text-muted">© 2017-2018</p><a class="btn btn-sm" th:href="@{/index.html(l='zh_CN')}">中文</a><a class="btn btn-sm" th:href="@{/index.html(l='en_US')}">English</a></form></body></html>
LoginController.java
@Controller
public class LoginController {@PostMapping("/user/login")public String login(@RequestParam("username") String username,@RequestParam("password") String password,Map<String,Object> map, HttpSession session){if(!StringUtils.isEmpty(username) && "123456".equals(password)){//登录成功//将登录的用户名放到session中session.setAttribute("loginUser",username);//登陆成功,防止表单重复提交,可以重定向到主页return "redirect:/main.html";}else {//登录失败map.put("msg","用户名密码错误");return "login";}}
}
LoginHandlerInterceptor.java
/*** 登陆检查拦截器,*/
public class LoginHandlerInterceptor implements HandlerInterceptor {//目标方法执行之前@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {Object user = request.getSession().getAttribute("loginUser");if(user == null){//未登陆,返回登陆页面request.setAttribute("msg","没有权限请先登陆");request.getRequestDispatcher("/index.html").forward(request,response);return false;}else{//已登陆,放行请求return true;}}
}
MyMVCConfig.java
//使用WebMvcConfigurerAdapter可以来扩展SpringMVC的功能
@Configuration
public class MyMVCConfig extends WebMvcConfigurerAdapter {//所有的WebMvcConfigurerAdapter组件都会一起起作用@Bean //将组件注册在容器public WebMvcConfigurerAdapter webMvcConfigurerAdapter(){WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() {@Overridepublic void addViewControllers(ViewControllerRegistry registry) {registry.addViewController("/").setViewName("login");registry.addViewController("/index.html").setViewName("login");//加个视图映射,当发送/main.html请求的时候会跳转到dashboard页面registry.addViewController("/main.html").setViewName("dashboard");}//注册拦截器@Overridepublic void addInterceptors(InterceptorRegistry registry) {//将自定义的拦截器注册到容器中,设置拦截所有的请求,并将"/index.html","/","/user/login"请求都放开//SpringBoot1.X已经做好了静态资源映射 静态资源; *.css , *.js都不需要配置了//如果SpringBoot2.X就要放开静态资源的拦截registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**").excludePathPatterns("/index.html","/","/user/login","/asserts/css/**","/asserts/img/**","/asserts/js/**","/webjars/**");}};return adapter;}//将自定义的区域解析器注入到容器中@Beanpublic LocaleResolver localeResolver(){return new MyLocaleResolver();}
}
效果如下:
⑸ CRUD-员工列表
实验要求
1)、RestfulCRUD:CRUD满足Rest风格;
URI: /资源名称/资源标识 HTTP请求方式区分对资源CRUD操作
2)、实验的请求架构;
3)、员工列表:
thymeleaf公共页面元素抽取和引入的简单方式
① 抽取公共片段
<!--方式一--> <div th:fragment="copy"> © 2011 The Good Thymes Virtual Grocery </div> <!--方式二--> <div id="copy"> © 2011 The Good Thymes Virtual Grocery </div>
例如:
1. 使用~{templatename::fragmentname}:模板名::片段名
引入的抽取的方式:
2. 使用~{templatename::selector}:模板名::选择器
引入的抽取方式:
② 引入公共片段
<div th:insert="~{footer :: copy}"></div>
引入的方式有两种:
~{templatename::selector}:模板名::选择器
~{templatename::fragmentname}:模板名::片段名
注意:
①使用insert引入公共片段在div标签中
②如果使用th:insert等属性进行引入,可以不用写~{}:
行内写法可以加上:[[~{}]];[(~{})];
例如:
1. 使用~{templatename::fragmentname}:模板名::片段名
引入的方式:
2. 使用~{templatename::selector}:模板名::选择器
引入的方式:
三种引入公共片段的th属性:
th:insert:
将公共片段整个插入到声明引入的元素中
th:replace:
将声明引入的元素替换为公共片段
th:include:
将被引入的片段的内容包含进这个标签中<!--引入方式: --> <div th:insert="footer :: copy"></div> <div th:replace="footer :: copy"></div> <div th:include="footer :: copy"></div><!--效果--> <div><footer> © 2011 The Good Thymes Virtual Grocery </footer> </div><footer> © 2011 The Good Thymes Virtual Grocery </footer><div> © 2011 The Good Thymes Virtual Grocery </div>
引入片段的时候传入参数:使被点击的菜单栏高亮显示
<!--引入sidebar,并给侧边栏加上参数--> <div th:replace="commons/bar::#sidebar(activeUri='main.html')"></div><nav class="col-md-2 d-none d-md-block bg-light sidebar" id="sidebar"><div class="sidebar-sticky"><ul class="nav flex-column"><li class="nav-item"><a class="nav-link active" th:class="${activeUri == 'main.html' ? 'nav-link active' : 'nav-link'}" href="#" th:href="@{/main.html}"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-home"><path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path><polyline points="9 22 9 12 15 12 15 22"></polyline></svg>Dashboard <span class="sr-only">(current)</span></a></li>. . . </nav>
例如:
效果如下:
⑹ CRUD-员工添加
添加页面
<body>
<!--引入抽取的topbar-->
<!--模板名:会使用thymeleaf的前后缀配置规则进行解析-->
<div th:replace="commons/bar::topbar"></div><div class="container-fluid"><div class="row"><!--引入侧边栏--><div th:replace="commons/bar::#sidebar(activeUri='emps')"></div><main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4"><!--需要区分是员工修改还是添加;--><form th:action="@{/emp}" method="post"><!--发送put请求修改员工数据--><!--1、SpringMVC中配置HiddenHttpMethodFilter;(SpringBoot自动配置好的)2、页面创建一个post表单3、创建一个input项,name="_method";值就是我们指定的请求方式--><input type="hidden" name="_method" value="put" th:if="${emp!=null}"/><input type="hidden" name="id" th:if="${emp!=null}" th:value="${emp.id}"><div class="form-group"><label>LastName</label><input name="lastName" type="text" class="form-control" placeholder="请输入姓名" th:value="${emp!=null}?${emp.lastName}"></div><div class="form-group"><label>Email</label><input name="email" type="email" class="form-control" placeholder="请输入邮箱" th:value="${emp!=null}?${emp.email}"></div><div class="form-group"><label>Gender</label><br/><div class="form-check form-check-inline"><input class="form-check-input" type="radio" name="gender" value="1" th:checked="${emp!=null}?${emp.gender==1}"><label class="form-check-label">男</label></div><div class="form-check form-check-inline"><input class="form-check-input" type="radio" name="gender" value="0" th:checked="${emp!=null}?${emp.gender==0}"><label class="form-check-label">女</label></div></div><div class="form-group"><label>department</label><!--提交的是部门的id--><select class="form-control" name="department.id"><option th:selected="${emp!=null}?${dept.id == emp.department.id}" th:value="${dept.id}" th:each="dept:${depts}" th:text="${dept.departmentName}">1</option></select></div><div class="form-group"><label>Birth</label><input name="birth" type="text" class="form-control" placeholder="请输入生日" th:value="${emp!=null}?${#dates.format(emp.birth, 'yyyy-MM-dd HH:mm')}"></div><button type="submit" class="btn btn-primary" th:text="${emp!=null}?'修改':'添加'">添加</button></form></main></div>
</div><!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script type="text/javascript" src="asserts/js/jquery-3.2.1.slim.min.js" th:src="@{/webjars/jquery/3.3.1/jquery.js}"></script>
<script type="text/javascript" src="asserts/js/popper.min.js" th:src="@{/webjars/popper.js/1.11.1/dist/popper.js}"></script>
<script type="text/javascript" src="asserts/js/bootstrap.min.js" th:src="@{/webjars/bootstrap/4.0.0/js/bootstrap.js}"></script><!-- Icons -->
<script type="text/javascript" src="asserts/js/feather.min.js" th:src="@{/asserts/js/feather.min.js}"></script>
<script>feather.replace()
</script>
</body>
提交的数据格式不对:生日:日期;
2017-12-12;2017/12/12;2017.12.12;
日期的格式化;页面提交的值都是String字符串类型的SpringMVC将页面提交的值需要转换为指定类型的Date格式;
例如:
现在需要将页面2017-12-12类型的数据用Date类型的birth接收,会报错
2017-12-12—Date; 类型转换,格式化;
默认日期是按照/
的方式; 例如:2017/12/12
可以通过配置文件设置SpringMVC的日期转换类型格式
#指定SpringMVC将页面yyyy-MM-dd格式的转换成Date格式
spring.mvc.format.date=yyyy-MM-dd
⑺ CRUD-员工修改
修改添加二合一表单
<!--需要区分是员工修改还是添加;-->
<form th:action="@{/emp}" method="post"><!--发送put请求修改员工数据--><!--1、SpringMVC中配置HiddenHttpMethodFilter;(SpringBoot自动配置好的)2、页面创建一个post表单3、创建一个input项,name="_method";值就是我们指定的请求方式--><input type="hidden" name="_method" value="put" th:if="${emp!=null}"/><input type="hidden" name="id" th:if="${emp!=null}" th:value="${emp.id}"><div class="form-group"><label>LastName</label><input name="lastName" type="text" class="form-control" placeholder="请输入姓名" th:value="${emp!=null}?${emp.lastName}"></div><div class="form-group"><label>Email</label><input name="email" type="email" class="form-control" placeholder="请输入邮箱" th:value="${emp!=null}?${emp.email}"></div><div class="form-group"><label>Gender</label><br/><div class="form-check form-check-inline"><input class="form-check-input" type="radio" name="gender" value="1" th:checked="${emp!=null}?${emp.gender==1}"><label class="form-check-label">男</label></div><div class="form-check form-check-inline"><input class="form-check-input" type="radio" name="gender" value="0" th:checked="${emp!=null}?${emp.gender==0}"><label class="form-check-label">女</label></div></div><div class="form-group"><label>department</label><!--提交的是部门的id--><select class="form-control" name="department.id"><option th:selected="${emp!=null}?${dept.id == emp.department.id}" th:value="${dept.id}" th:each="dept:${depts}" th:text="${dept.departmentName}">1</option></select></div><div class="form-group"><label>Birth</label><input name="birth" type="text" class="form-control" placeholder="请输入生日" th:value="${emp!=null}?${#dates.format(emp.birth, 'yyyy-MM-dd HH:mm')}"></div><button type="submit" class="btn btn-primary" th:text="${emp!=null}?'修改':'添加'">添加</button>
</form>
修改添加二合一Service
public void save(Employee employee){if(employee.getId() == null){employee.setId(initId++);}employee.setDepartment(departmentDao.getDepartment(employee.getDepartment().getId()));employees.put(employee.getId(), employee);
}
1) SpringBoot实现form表单发送put请求的步骤:
- SpringMVC中配置HiddenHttpMethodFilter;(SpringBoot自动配置好的)
- 页面创建一个post表单
- 创建一个input项,name=“_method”;值就是我们指定的请求方式
⑻ CRUD-员工删除
删除页面:
<body><!--引入topbar--><div th:replace="commons/bar::topbar"></div><div class="container-fluid"><div class="row"><!--引入sidebar--><div th:replace="commons/bar::#sidebar(activeUri='emps')"></div><main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4"><h2><a class="btn btn-sm btn-success" href="emp" th:href="@{/emp}">员工添加</a></h2><div class="table-responsive"><table class="table table-striped table-sm"><thead><tr><th>#</th><th>lastName</th><th>email</th><th>gender</th><th>department</th><th>birth</th><th>操作</th></tr></thead><tbody><tr th:each="emp:${emps}"><td th:text="${emp.id}"></td><td>[[${emp.lastName}]]</td><td th:text="${emp.email}"></td><td th:text="${emp.gender}==0?'女':'男'"></td><td th:text="${emp.department.departmentName}"></td><td th:text="${#dates.format(emp.birth, 'yyyy-MM-dd HH:mm')}"></td><td><a class="btn btn-sm btn-primary" th:href="@{/emp/}+${emp.id}">编辑</a><!--给button按钮自定义了一个del_uri的属性,属性的值通过表达式拼接的及:/emp/emp.id--><button th:attr="del_uri=@{/emp/}+${emp.id}" class="btn btn-sm btn-danger deleteBtn">删除</button></td></tr></tbody></table></div></main><form id="deleteEmpForm" method="post"><input type="hidden" name="_method" value="delete"/></form></div></div><script type="text/javascript" src="asserts/js/jquery-3.2.1.slim.min.js" th:src="@{/webjars/jquery/3.3.1/jquery.js}"></script><script type="text/javascript" src="asserts/js/popper.min.js" th:src="@{/webjars/popper.js/1.11.1/dist/popper.js}"></script><script type="text/javascript" src="asserts/js/bootstrap.min.js" th:src="@{/webjars/bootstrap/4.0.0/js/bootstrap.js}"></script><!-- Icons --><script type="text/javascript" src="asserts/js/feather.min.js" th:src="@{/asserts/js/feather.min.js}"></script><script>feather.replace()</script><script>$(".deleteBtn").click(function(){//点击删除按钮的时候将deleteEmpForm表单的action的值替换成自定义属性的值,并通过submit提交给Controller,从而删除当前员工(this表示当前删除按钮对象)$("#deleteEmpForm").attr("action",$(this).attr("del_uri")).submit();return false;});</script>
</body>
controller
//员工删除
@DeleteMapping("/emp/{id}")
public String deleteEmployee(@PathVariable("id") Integer id){employeeDao.delete(id);return "redirect:/emps";
}
springboot2.x要注意在配置文件配置hiddenmethodfilter生效
spring.mvc.hiddenmethod.filter.enabled=true
6. 错误处理机制
⑴ SpringBoot默认的错误处理机制
默认效果:
1) 浏览器
- 返回一个默认的错误页面
- 浏览器发送请求的请求头:
2)如果是其他客户端
- 默认响应一个json数据
postman模拟客户端发送请求的请求头:
⑵ SpringBoot默认的错误处理机制原理:
1) 可以参照ErrorMvcAutoConfiguration;错误处理的自动配置;
给容器中添加了以下组件
① DefaultErrorAttributes:
在这里插入代码片
② BasicErrorController:
@Controller
@RequestMapping({"${server.error.path:${error.path:/error}}"})
public class BasicErrorController extends AbstractErrorController {. . .@RequestMapping(produces = {"text/html"}//产生html类型的数据;浏览器发送的请求来到这个方法处理)public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {HttpStatus status = this.getStatus(request);Map<String, Object> model = Collections.unmodifiableMap(this.getErrorAttributes(request, this.getErrorAttributeOptions(request, MediaType.TEXT_HTML)));response.setStatus(status.value());//去哪个页面作为错误页面;包含页面地址和页面内容ModelAndView modelAndView = this.resolveErrorView(request, response, status, model);return modelAndView != null ? modelAndView : new ModelAndView("error", model);}@RequestMappingpublic ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {HttpStatus status = this.getStatus(request);if (status == HttpStatus.NO_CONTENT) {return new ResponseEntity(status);} else {Map<String, Object> body = this.getErrorAttributes(request, this.getErrorAttributeOptions(request, MediaType.ALL));return new ResponseEntity(body, status);}}
③ ErrorPageCustomizer:
@Value("${error.path:/error}")
private String path = "/error";//系统出现错误以后来到error请求进行处理;(web.xml注册的错误页 面规则)
④ DefaultErrorViewResolver:
public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) {ModelAndView modelAndView = this.resolve(String.valueOf(status.value()), model);if (modelAndView == null && SERIES_VIEWS.containsKey(status.series())) {modelAndView = this.resolve((String)SERIES_VIEWS.get(status.series()), model);}return modelAndView;}private ModelAndView resolve(String viewName, Map<String, Object> model) {//默认SpringBoot可以去找到一个页面? error/404String errorViewName = "error/" + viewName;//模板引擎可以解析这个页面地址就用模板引擎解析TemplateAvailabilityProvider provider = this.templateAvailabilityProviders.getProvider(errorViewName, this.applicationContext);//模板引擎可用的情况下返回到errorViewName指定的视图地址//模板引擎不可用,就在静态资源文件夹下找errorViewName对应的页面 error/404.htmlreturn provider != null ? new ModelAndView(errorViewName, model) : this.resolveResource(errorViewName, model);}
2)ErrorMvcAutoConfiguration
处理步骤:
一但系统出现4xx或者5xx之类的错误;就会生效(定制错误的响应规则);就会来到/error 请求;就会被BasicErrorController处理;
响应页面;去哪个页面是由DefaultErrorViewResolver解析得到的;
protected ModelAndView resolveErrorView(HttpServletRequest request, HttpServletResponse response, HttpStatus status, Map<String, Object> model) {//所有的ErrorViewResolver得到ModelAndViewIterator var5 = this.errorViewResolvers.iterator();ModelAndView modelAndView;do {if (!var5.hasNext()) {return null;}ErrorViewResolver resolver = (ErrorViewResolver)var5.next();modelAndView = resolver.resolveErrorView(request, status, model);} while(modelAndView == null);return modelAndView;
}
⑶ 如果定制错误响应:
1)有模板引擎的情况下;error/状态码; 【将错误页面命名为 错误状态码.html 放在模板引擎文件夹里面的 error文件夹下】,发生此状态码的错误就会来到 对应的页面;
我们可以使用4xx和5xx作为错误页面的文件名来匹配这种类型的所有错误,精确优先(优先寻找精确的状态 码.html);
页面能获取的信息:
timestamp:时间戳
status:状态码
error:错误提示
exception:异常对象
message:异常消息
errors:JSR303数据校验的错误都在这里
<!DOCTYPE html>
<!-- saved from url=(0052)http://getbootstrap.com/docs/4.0/examples/dashboard/ -->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>. . .
</head>
<div class="container-fluid"><div class="row">. . .<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4"><h1>status:[[${status}]]</h1><h2>timestamp:[[${timestamp}]]</h2></main></div>
</div>
效果如下:
2)、没有模板引擎(模板引擎找不到这个错误页面),静态资源文件夹下找;
3)、以上都没有错误页面,就是默认来到SpringBoot默认的错误提示页面;
⑷ 如何定制错误的json数据;
1)、自定义异常处理&返回定制json数据(没有自适应效果…);
① 自定义异常UserNotExistException
public class UserNotExistException extends RuntimeException {public UserNotExistException() {super("用户不存在");}
}
② 自定义异常处理器MyExceptionHandler
@ControllerAdvice
public class MyExceptionHandler {//浏览器客户端返回的都是json@ResponseBody@ExceptionHandler(UserNotExistException.class)public Map<String,Object> handleException(Exception e){Map<String,Object> map = new HashMap<>();map.put("code","user.notexist");map.put("message",e.getMessage());return map;}
}
//没有自适应效果...
③ 在HelloController中模拟抛自定义异常
@Controller
public class HelloController {@ResponseBody@RequestMapping("/hello")public String hello(@RequestParam("user") String user){if(user.equals("aaa")){throw new UserNotExistException();}return "Hello World";}
}
④ 获取SpringBoot的异常对象exception和message信息,springboot1.x的版本可以不用设置,但用的是2.x的必须进行相应的设置
#获取SpringBoot的异常对象exception和message信息,springboot1.x的版本可以不用设置,但用的是2.x的必须设置
server.error.include-exception=true
server.error.include-message=always
效果如下:
浏览器:
postman模拟客户端:
2)转发到/error进行自适应响应效果处理
① 自定义异常UserNotExistException
public class UserNotExistException extends RuntimeException {public UserNotExistException() {super("用户不存在");}
}
② 自定义异常处理器MyExceptionHandler
@ExceptionHandler(UserNotExistException.class)public String handleException(Exception e, HttpServletRequest request){Map<String,Object> map = new HashMap<>();//传入我们自己的错误状态码 4xx 5xx,否则就不会进入定制错误页面的解析流程/*** Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");*/request.setAttribute("javax.servlet.error.status_code",500);map.put("code","user.notexist");map.put("message","用户出错啦");//转发到/error,让BasicErrorController进行处理return "forward:/error";}
错误状态码key的由来:
③ 在HelloController中模拟抛自定义异常
@Controller
public class HelloController {@ResponseBody@RequestMapping("/hello")public String hello(@RequestParam("user") String user){if(user.equals("aaa")){throw new UserNotExistException();}return "Hello World";}
}
④ 获取SpringBoot的异常对象exception和message信息,springboot1.x的版本可以不用设置,但用的是2.x的必须进行相应的设置
#获取SpringBoot的异常对象exception和message信息,springboot1.x的版本可以不用设置,但用的是2.x的必须设置
server.error.include-exception=true
server.error.include-message=always
效果如下:
浏览器:
postman模拟客户端:
7. 配置嵌入式Servlet容器
SpringBoot默认使用Tomcat作为嵌入式的Servlet容器;
⑴ 如何定制和修改Servlet容器的相关配置;
1)在配置文件中修改和server有关的配置
# 应用服务 WEB 访问端口
server.port=8081
#设置项目项目根路径
server.servlet.context-path=/
#设置tomcat的字符编码
server.tomcat.uri-encoding=UTF-8//通用的Servlet容器设置 server.xxx
//Tomcat的设置 server.tomcat.xxx
设置原理如下:
2)编写一个EmbeddedServletContainerCustomizer嵌入式的Servlet容器的定制器;来修改Servlet容器的 配(Spring Boot2.0以上版本EmbeddedServletContainerCustomizer被WebServerFactoryCustomizer替代)
1.x版本
//配置嵌入式的Servlet容器 @Bean public EmbeddedServletContainerCustomizer embeddedServletContainerCustomizer(){return new EmbeddedServletContainerCustomizer() {//定制嵌入式的Servlet容器相关的规则@Overridepublic void customize(ConfigurableEmbeddedServletContainer container) {container.setPort(8083);}}; }
2.x版本
//配置嵌入式的Servlet容器@Beanpublic WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer(){return new WebServerFactoryCustomizer<ConfigurableWebServerFactory>() {@Overridepublic void customize(ConfigurableWebServerFactory factory) {factory.setPort(8888);}};}
⑵ 注册Servlet三大组件【Servlet、Filter、Listener】
由于SpringBoot默认是以jar包的方式启动嵌入式的Servlet容器来启动SpringBoot的web应用,没有web.xml文 件。
注册三大组件用以下方式
1) 注册自定义的Servlet的步骤
① 编写自定义的servlet
public class MyServlet extends HttpServlet {//处理get请求@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doPost(req,resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {resp.getWriter().write("Hello MyServlet");}
}
② 通过配置ServletRegistrationBean将自定义的servlet注册到容器中
@Configuration
public class MyServerConfig {//注册三大组件@Beanpublic ServletRegistrationBean myServlet(){ServletRegistrationBean registrationBean = new ServletRegistrationBean(new MyServlet(),"/myServlet");registrationBean.setLoadOnStartup(1);return registrationBean;}
}
效果如下:
2)注册自定义的Filter的步骤
① 编写自定义的Filter
public class MyFilter implements Filter {@Overridepublic void init(FilterConfig filterConfig) throws ServletException {}@Overridepublic void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {System.out.println("MyFilter process...");chain.doFilter(request,response);}@Overridepublic void destroy() {}
}
② 通过配置FilterRegistrationBean将自定义的Filter注册到容器中
@Configuration
public class MyServerConfig {@Beanpublic FilterRegistrationBean myFilter(){FilterRegistrationBean registrationBean = new FilterRegistrationBean();registrationBean.setFilter(new MyFilter());registrationBean.setUrlPatterns(Arrays.asList("/hello","/myServlet"));return registrationBean;}
}
效果如下:
3)注册自定义的Listener的步骤
① 编写自定义的Listener
public class MyListener implements ServletContextListener {@Overridepublic void contextInitialized(ServletContextEvent sce) {System.out.println("contextInitialized...web应用启动");}@Overridepublic void contextDestroyed(ServletContextEvent sce) {System.out.println("contextDestroyed...当前web项目销毁");}
}
② 通过配置ServletListenerRegistrationBean将自定义的Listener注册到容器中
@Configuration
public class MyServerConfig {@Beanpublic ServletListenerRegistrationBean myListener(){ServletListenerRegistrationBean<MyListener> registrationBean = new ServletListenerRegistrationBean<>(new MyListener());return registrationBean;}
}
效果如下:
⑶ SpringBoot帮我们自动配置SpringMVC的时候,自动的注册SpringMVC的前端控制器DIspatcherServlet;
DispatcherServletAutoConfiguration中:
@Configuration(proxyBeanMethods = false)@Conditional({DispatcherServletAutoConfiguration.DispatcherServletRegistrationCondition.class})@ConditionalOnClass({ServletRegistration.class})@EnableConfigurationProperties({WebMvcProperties.class})@Import({DispatcherServletAutoConfiguration.DispatcherServletConfiguration.class})protected static class DispatcherServletRegistrationConfiguration {protected DispatcherServletRegistrationConfiguration() {}@Bean(name = {"dispatcherServletRegistration"})@ConditionalOnBean(value = {DispatcherServlet.class},name = {"dispatcherServlet"})public DispatcherServletRegistrationBean dispatcherServletRegistration(DispatcherServlet dispatcherServlet, WebMvcProperties webMvcProperties, ObjectProvider<MultipartConfigElement> multipartConfig) {//默认拦截: / 所有请求;包静态资源,但是不拦截jsp请求; /*会拦截jsp //可以通过server.servletPath来修改SpringMVC前端控制器默认拦截的请求路径DispatcherServletRegistrationBean registration = new DispatcherServletRegistrationBean(dispatcherServlet, webMvcProperties.getServlet().getPath());registration.setName("dispatcherServlet");registration.setLoadOnStartup(webMvcProperties.getServlet().getLoadOnStartup());multipartConfig.ifAvailable(registration::setMultipartConfig);return registration;}}
⑷ SpringBoot替换为其他嵌入式Servlet容器,默认支持Tomcat(默认使用)、Jetty(长连接,常用作聊天功能的服务器)、Undertow(不支持JSP)
默认支持Tomcat(默认使用)、Jetty(长连接,常用作聊天功能的服务器)、Undertow(不支持JSP)
Tomcat(默认使用)
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>引入web模块默认就是使用嵌入式的Tomcat作为Servlet容器; </dependency>
效果如下:
Jetty(长连接,常用作聊天功能的服务器
<!--引入web模块--> <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><!--将spring-boot-starter-web 中的tomcat排除--><exclusions><exclusion><artifactId>spring-boot-starter-tomcat</artifactId><groupId>org.springframework.boot</groupId></exclusion></exclusions> </dependency> <!--引入其他的Servlet容器--> <dependency><artifactId>spring-boot-starter-jetty</artifactId><groupId>org.springframework.boot</groupId> </dependency>
效果如下:
Undertow(不支持JSP)
<!--引入web模块--> <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><exclusions><exclusion><artifactId>spring-boot-starter-tomcat</artifactId><groupId>org.springframework.boot</groupId></exclusion></exclusions> </dependency> <!--引入其他的Servlet容器--> <dependency><artifactId>spring-boot-starter-undertow</artifactId><groupId>org.springframework.boot</groupId> </dependency>
8. 使用外置的Servlet容器
⑴ 嵌入式Servlet容器:应用打成可执行的jar
优点: 简单、便携;
缺点:默认不支持JSP、优化定制比较复杂
⑵ 外置的Servlet容器:
外面安装Tomcat—应用war包的方式打包;
⑶ SpringBoot使用外置的Servlet容器步骤
1)必须创建一个war项目;(利用idea创建好目录结构)
2)将嵌入式的Tomcat指定为provided;
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-tomcat</artifactId><scope>provided</scope>
</dependency>
3)必须编写一个SpringBootServletInitializer的子类,并调用configure方法
public class ServletInitializer extends SpringBootServletInitializer {@Overrideprotected SpringApplicationBuilder configure(SpringApplicationBuilder application) {//传入SpringBoot应用的主程序return application.sources(SpringbootOutlayTomcatApplication.class);}}
4)启动服务器就可以使用;
⑷ SpringBoot使用servlet容器的原理
jar包: 执行SpringBoot主类的main方法,启动ioc容器,创建嵌入式的Servlet容器;
war包: 启动服务器,服务器启动SpringBoot应用【SpringBootServletInitializer】,启动ioc容器;
1)war包 启动服务器规则:
① 服务器启动(web应用启动)会创建当前web应用里面每一个jar包里面ServletContainerInitializer实例:
② ServletContainerInitializer的实现放在jar包的META-INF/services文件夹下,有一个名为 javax.servlet.ServletContainerInitializer的文件,内容就是ServletContainerInitializer的实现类的全类名
③ 还可以使用@HandlesTypes,在应用启动的时候加载我们感兴趣的类;
2)war包 启动服务器流程:
① 启动Tomcat
② org\springframework\spring-web\4.3.14.RELEASE\spring-web-4.3.14.RELEASE.jar!\META-INF\services\javax.servlet.ServletContainerInitializer:
Spring的web模块里面有这个文件:org.springframework.web.SpringServletContainerInitializer
③ SpringServletContainerInitializer将@HandlesTypes(WebApplicationInitializer.class)标注的所有这个类型 的类都传入到onStartup方法的Set<Class<?>>
;为这些WebApplicationInitializer类型的类创建实例;
④ 每一个WebApplicationInitializer都调用自己的onStartup;
⑤ 相当于我们的SpringBootServletInitializer的类会被创建对象,并执行onStartup方法
⑥ SpringBootServletInitializer实例执行onStartup的时候会createRootApplicationContext;创建容器
protected WebApplicationContext createRootApplicationContext(ServletContext servletContext) {//1、创建SpringApplicationBuilderSpringApplicationBuilder builder = this.createSpringApplicationBuilder();builder.main(this.getClass());ApplicationContext parent = this.getExistingRootWebApplicationContext(servletContext);if (parent != null) {this.logger.info("Root context already created (using as parent).");servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, (Object)null);builder.initializers(new ApplicationContextInitializer[]{new ParentContextApplicationContextInitializer(parent)});}builder.initializers(new ApplicationContextInitializer[]{new ServletContextApplicationContextInitializer(servletContext)});builder.contextClass(AnnotationConfigServletWebServerApplicationContext.class);//调用configure方法,子类重写了这个方法,将SpringBoot的主程序类传入了进来builder = this.configure(builder);builder.listeners(new ApplicationListener[]{new SpringBootServletInitializer.WebEnvironmentPropertySourceInitializer(servletContext)});//使用builder创建一个Spring应用SpringApplication application = builder.build();if (application.getAllSources().isEmpty() && MergedAnnotations.from(this.getClass(), SearchStrategy.TYPE_HIERARCHY).isPresent(Configuration.class)) {application.addPrimarySources(Collections.singleton(this.getClass()));}Assert.state(!application.getAllSources().isEmpty(), "No SpringApplication sources have been defined. Either override the configure method or add an @Configuration annotation");if (this.registerErrorPageFilter) {application.addPrimarySources(Collections.singleton(ErrorPageFilterConfiguration.class));}application.setRegisterShutdownHook(false);//启动Spring应用return this.run(application);}
⑦ Spring的应用就启动并且创建IOC容器
public ConfigurableApplicationContext run(String... args) {StopWatch stopWatch = new StopWatch();stopWatch.start();ConfigurableApplicationContext context = null;Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList();this.configureHeadlessProperty();SpringApplicationRunListeners listeners = this.getRunListeners(args);listeners.starting();Collection exceptionReporters;try {ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments);this.configureIgnoreBeanInfo(environment);Banner printedBanner = this.printBanner(environment);context = this.createApplicationContext();exceptionReporters = this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context);this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);//刷新IOC容器this.refreshContext(context);this.afterRefresh(context, applicationArguments);stopWatch.stop();if (this.logStartupInfo) {(new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), stopWatch);}listeners.started(context);this.callRunners(context, applicationArguments);} catch (Throwable var10) {this.handleRunFailure(context, var10, exceptionReporters, listeners);throw new IllegalStateException(var10);}try {listeners.running(context);return context;} catch (Throwable var9) {this.handleRunFailure(context, var9, exceptionReporters, (SpringApplicationRunListeners)null);throw new IllegalStateException(var9);}}
⑤⑥⑦如下:
启动Servlet容器,再启动SpringBoot应用
七、Docker容器
1.简介
Docker 是一个开源的应用容器引擎,基于 Go 语言 并遵从Apache2.0协议开源。
Docker 可以让开发者打包他们的应用以及依赖包到一个轻量级、可移植的容器中,然后发布到任何流行的 Linux 机器上,也可以实现虚拟化。
容器是完全使用沙箱机制,相互之间不会有任何接口,更重要的是容器性能开销极低。
Docker支持将软件编译成一个镜像;然后在镜像中各种软件做好配置,将镜像发布出去,其他使用者可以直接使用这个镜像。运行中的这个镜像称为容器,容器启动是非常快速的。类似windows里面的ghost操作系统,安装好后什么都有了;
Docker和windows镜像ghost对比:
2.核心概念
docker主机(Host) :安装了Docker程序的机器(Docker直接安装在操作系统之上);
docker客户端(Client):连接docker主机进行操作;
docker仓库(Registry):Docker 仓库用来保存镜像,可以理解为代码控制中的代码仓库。Docker Hub(https://hub.docker.com) 提供了庞大的镜像集合供使用。
docker镜像(Images):软件打包好的镜像;放在docker仓库中;
docker容器(Container):镜像启动后的实例称为一个容器;容器是独立运行的一个或一组应用
3.使用Docker的步骤:
1)、安装Docker
2)、去Docker仓库找到这个软件对应的镜像;
3)、使用Docker运行这个镜像,这个镜像就会生成一个Docker容器;
4)、对容器的启动停止就是对软件的启动停止;
4.安装Docker
⑴ 安装linux虚拟机
⑵ 在linux虚拟机上安装docker
1、检查内核版本,必须是3.10及以上
检查内核版本,必须是3.10及以上
[root@localhost ~]# uname -a
2、安装docker
安装docker
yum install docker
输入y确认安装
3、启动docker和查看docker版本
启动docker
[root@localhost ~]# systemctl start docker
查看docker版本
[root@localhost ~]# docker --version
4、开机启动docker
开机启动docker
[root@localhost ~]# systemctl enable docker
6、停止docker
[root@localhost ~]# systemctl stop docker
5. Docker常用命令&操作
⑴ 镜像操作
1、镜像检索
docker search 关键字
[root@localhost ~]# docker search mysql
我们经常去docker hub上检索镜像的详细信息,如镜 像的TAG。
https://hub.docker.com/
2、拉取镜像名
docker pull 镜像名:tag
:tag是可选的,tag表示标签,多为软件的版本,默认是latest
[root@localhost ~]# docker pull mysql
[root@localhost ~]# docker pull mysql:5.7.37
3、查看所有本地镜像
docker images
[root@localhost ~]# docker images
4、删除指定的本地镜像
docker rmi image-id
[root@localhost ~]# docker rmi c8973bcead14
⑵ docker容器操作
类似于软件的安装:
软件镜像(QQ安装程序)----运行镜像----产生一个容器(正在运行的软件,运行的QQ);
docker容器启动的完整步骤:
1、搜索镜像
[root@localhost ~]# docker search tomcat
也可以通过https://hub.docker.com/搜索
2、拉取镜像
[root@localhost ~]# docker pull tomcat
3、查看镜像
[root@localhost ~]# docker images
4、根据镜像启动容器
docker run --name container-name -d image-name:tag
–name:自定义容器名
-d:后台运行
image-name:指定镜像模板
tag表示标签,多为软件的版本,默认是latest
[root@localhost ~]# docker run --name mytomcat -d tomcat:latest
5、查看docker中运行的容器
[root@localhost ~]# docker ps
6、 停止运行中的容器
docker stop 容器的名称/容器的id
[root@localhost ~]# docker stop 67dc7733d85e
7、查看所有的容器
[root@localhost ~]# docker ps -a
8、启动容器
docker start 容器的名称/容器的id
[root@localhost ~]# docker start 67dc7733d85e
9、删除容器(删除容器前必须要关闭容器)
docker rm 容器的id
[root@localhost ~]# docker rm 67dc7733d85e
10、启动一个做了端口映射的tomcat
docker run -d -p 主机端口:容器内部的端口 image-name:tag
-d:后台运行
‐p: 将主机的端口映射到容器的一个端口 主机端口:容器内部的端口
:tag表示标签,多为软件的版本,默认是lates
image-name:指定镜像模板
tag表示标签,多为软件的版本,默认是latest
[root@localhost ~]# docker run -d -p 8888:8080 tomcat:latest
11、为了演示简单关闭了linux的防火墙
查看防火墙状态
service firewalld status
关闭防火墙
service firewalld stop
访问tomcat效果如下:
12、查看容器的日志
[root@localhost ~]# docker logs 5f6bbd37b99b
更多命令参看:
https://docs.docker.com/engine/reference/commandline/docker/
八、SpringBoot与数据访问
1. SpringBoot整合MyBatis(使用druid数据库驱动)
创建项目
⑴ 配置文件中数据源的相关配置都在DataSourceProperties里面
⑵ SpringBoot关于数据源的自动配置原理:
SpringBoot关于数据源的自动配置都在org.springframework.boot.autoconfigure.jdbc下:
参考
DataSourceConfiguration
,根据配置创建数据源,可以使用spring.datasource.type
指定自定义的数据源类型;org.apache.commons.dbcp2.BasicDataSource、com.zaxxer.hikari.HikariDataSource、org.apache.tomcat.jdbc.pool.DataSource
自定义数据源类型
@Configuration(proxyBeanMethods = false)@ConditionalOnMissingBean({DataSource.class})@ConditionalOnProperty(name = {"spring.datasource.type"})static class Generic {Generic() {}@BeanDataSource dataSource(DataSourceProperties properties) {//使用DataSourceBuilder创建数据源,利用反射创建响应type的数据源,并且绑定相关属性return properties.initializeDataSourceBuilder().build();}}
⑶ 整合Druid数据源
pom
<dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.2.8</version>
</dependency>
application.yml
spring:datasource:username: rootpassword: 123456url: jdbc:mysql://192.168.15.22:3306/jdbcdriver-class-name: com.mysql.cj.jdbc.Drivertype: com.alibaba.druid.pool.DruidDataSourceinitialSize: 5minIdle: 5maxActive: 20maxWait: 60000timeBetweenEvictionRunsMillis: 60000minEvictableIdleTimeMillis: 300000validationQuery: SELECT 1 FROM DUALtestWhileIdle: truetestOnBorrow: falsetestOnReturn: falsepoolPreparedStatements: true# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙filters: stat,wall,log4jmaxPoolPreparedStatementPerConnectionSize: 20useGlobalDataSourceStat: trueconnectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
DruidConfig.java
@Configuration
public class DruidConfig {//使配置文件中的相关配置生效@ConfigurationProperties(prefix = "spring.datasource")@Beanpublic DataSource druid(){return new DruidDataSource();}//配置Druid的监控//1、配置一个管理后台的Servlet@Beanpublic ServletRegistrationBean statViewServlet(){ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");Map<String,String> initParams = new HashMap<>();initParams.put("loginUsername","admin");//登录的用户名initParams.put("loginPassword","123456");//登录的密码initParams.put("allow","");//默认就是允许所有访问initParams.put("deny","192.168.15.21");//拒绝访问的ip地址bean.setInitParameters(initParams);return bean;}//2、配置一个web监控的filter@Beanpublic FilterRegistrationBean webStatFilter(){FilterRegistrationBean bean = new FilterRegistrationBean();bean.setFilter(new WebStatFilter());Map<String,String> initParams = new HashMap<>();initParams.put("exclusions","*.js,*.css,/druid/*");//设置哪些资源不拦截bean.setInitParameters(initParams);bean.setUrlPatterns(Arrays.asList("/*"));//拦截所有请求return bean;}
}
效果如下:
⑷ 整合MyBatis
pom.xml
<dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.1.4</version>
</dependency>
mybatis-spring-boot-starter引入的依赖关系:
① mybatis通过纯注解的方式操作数据库
DepartmentMapper.java
//指定这是一个操作数据库的mapper
@Mapper
public interface DepartmentMapper {@Select("select * from department where id=#{id}")Department getDeptById(Integer id);@Delete("delete from department where id=#{id}")int deleteDeptById(Integer id);@Options(useGeneratedKeys = true,keyProperty = "id")//参数数据后是返回主键值useGeneratedKeys表示是否是自增逐渐,keyProperty表示对应的实体主键名称@Insert("insert into department(departmentName) values(#{departmentName})")int insertDept(Department department);@Update("update department set department_name=#{departmentName} where id=#{id}")int updateDept(Department department);
}
结果如下:
问题一:怎么通过配置类的方式开启驼峰命名,解决实体属性名和数据库字段名不一致的问题
自定义MyBatis的配置规则;给容器中添加一个ConfigurationCustomizer,设置开启驼峰命名
@org.springframework.context.annotation.Configuration public class MyBatisConfig {@Beanpublic ConfigurationCustomizer configurationCustomizer(){return new ConfigurationCustomizer(){@Overridepublic void customize(Configuration configuration) {//开启驼峰命名,使实体属性和数据库字段能够对应上configuration.setMapUnderscoreToCamelCase(true);}};} }
问题二:可以省略*Mapper上的@Mapper注解,同意在启动类上加
@MapperScan("com.kejizhentan.springbootmybatisproject.mapper") @SpringBootApplication public class SpringbootMybatisProjectApplication {public static void main(String[] args) {SpringApplication.run(SpringbootMybatisProjectApplication.class, args);}}
② mybatis通过配置文件版操作数据库
mybatis:# 指定全局配置文件位置config-location: classpath:mybatis/mybatis-config.xml# 指定sql映射文件位置mapper-locations: classpath:mybatis/mapper/*.xml
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><!--在mybatis全局配置文件中配置开启驼峰命名--><settings><setting name="mapUnderscoreToCamelCase" value="true"/></settings>
</configuration>
EmployeeMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.kejizhentan.springbootmybatisproject.mapper.EmployeeMapper"><select id="getEmpById" resultType="com.kejizhentan.springbootmybatisproject.bean.Employee">SELECT * FROM employee WHERE id=#{id}</select><insert id="insertEmp">INSERT INTO employee(lastName,email,gender,d_id) VALUES (#{lastName},#{email},#{gender},#{dId})</insert>
</mapper>
注意:
mybatis通过配置文件操作数据库时,开启驼峰命名的配置是在mybatis-config.xml
全局配置文件中配置的
springBoot整合mybatis操作数据库,使用配置文件或者使用注解的的方式二者是兼容的:详细代码如下:
项目结构如下:
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.kejizhentan</groupId><artifactId>springboot-mybatis-project</artifactId><version>0.0.1-SNAPSHOT</version><name>springboot-mybatis-project</name><description>Demo project for Spring Boot</description><properties><java.version>1.8</java.version><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><spring-boot.version>2.3.7.RELEASE</spring-boot.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.1.4</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.2.8</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope><exclusions><exclusion><groupId>org.junit.vintage</groupId><artifactId>junit-vintage-engine</artifactId></exclusion></exclusions></dependency></dependencies><dependencyManagement><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-dependencies</artifactId><version>${spring-boot.version}</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement><build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.8.1</version><configuration><source>1.8</source><target>1.8</target><encoding>UTF-8</encoding></configuration></plugin><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><version>2.3.7.RELEASE</version><configuration><mainClass>com.kejizhentan.springbootmybatisproject.SpringbootMybatisProjectApplication</mainClass></configuration><executions><execution><id>repackage</id><goals><goal>repackage</goal></goals></execution></executions></plugin></plugins></build>
</project>
application.yml
spring:datasource:username: rootpassword: 123456url: jdbc:mysql://localhost:3306/kjzt?serverTimezone=UTCdriver-class-name: com.mysql.cj.jdbc.Drivertype: com.alibaba.druid.pool.DruidDataSourceinitialSize: 5minIdle: 5maxActive: 20maxWait: 60000timeBetweenEvictionRunsMillis: 60000minEvictableIdleTimeMillis: 300000validationQuery: SELECT 1 FROM DUALtestWhileIdle: truetestOnBorrow: falsetestOnReturn: falsepoolPreparedStatements: true# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙filters: stat,wall,log4jmaxPoolPreparedStatementPerConnectionSize: 20useGlobalDataSourceStat: trueconnectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500mybatis:# 指定全局配置文件位置config-location: classpath:mybatis/mybatis-config.xml# 指定sql映射文件位置mapper-locations: classpath:mybatis/mapper/*.xml
Department.java
public class Department {private Integer id;private String departmentName;public void setId(Integer id) {this.id = id;}public void setDepartmentName(String departmentName) {this.departmentName = departmentName;}public Integer getId() {return id;}public String getDepartmentName() {return departmentName;}
}
Employee.java
public class Employee {private Integer id;private String lastName;private Integer gender;private String email;private Integer dId;public void setId(Integer id) {this.id = id;}public void setLastName(String lastName) {this.lastName = lastName;}public void setGender(Integer gender) {this.gender = gender;}public void setEmail(String email) {this.email = email;}public void setdId(Integer dId) {this.dId = dId;}public Integer getId() {return id;}public String getLastName() {return lastName;}public Integer getGender() {return gender;}public String getEmail() {return email;}public Integer getdId() {return dId;}
}
DepartmentMapper.java
//指定这是一个操作数据库的mapper
//@Mapper
public interface DepartmentMapper {@Select("select * from department where id=#{id}")Department getDeptById(Integer id);@Delete("delete from department where id=#{id}")int deleteDeptById(Integer id);@Options(useGeneratedKeys = true,keyProperty = "id")//参数数据后是返回主键值useGeneratedKeys表示是否是自增逐渐,keyProperty表示对应的实体主键名称@Insert("insert into department(department_name) values(#{departmentName})")int insertDept(Department department);@Update("update department set department_name=#{departmentName} where id=#{id}")int updateDept(Department department);
}
EmployeeMapper.java
//@Mapper或者@MapperScan将接口扫描装配到容器中
public interface EmployeeMapper {public Employee getEmpById(Integer id);public void insertEmp(Employee employee);
}
DruidConfig.java
@Configuration
public class DruidConfig {//使配置文件中的相关配置生效@ConfigurationProperties(prefix = "spring.datasource")@Beanpublic DataSource druid(){return new DruidDataSource();}//配置Druid的监控//1、配置一个管理后台的Servlet@Beanpublic ServletRegistrationBean statViewServlet(){ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");Map<String,String> initParams = new HashMap<>();initParams.put("loginUsername","admin");//登录的用户名initParams.put("loginPassword","123456");//登录的密码initParams.put("allow","");//默认就是允许所有访问initParams.put("deny","192.168.15.21");//拒绝访问的ip地址bean.setInitParameters(initParams);return bean;}//2、配置一个web监控的filter@Beanpublic FilterRegistrationBean webStatFilter(){FilterRegistrationBean bean = new FilterRegistrationBean();bean.setFilter(new WebStatFilter());Map<String,String> initParams = new HashMap<>();initParams.put("exclusions","*.js,*.css,/druid/*");//设置哪些资源不拦截bean.setInitParameters(initParams);bean.setUrlPatterns(Arrays.asList("/*"));//拦截所有请求return bean;}
}
MyBatisConfig.java
@org.springframework.context.annotation.Configuration
public class MyBatisConfig {@Beanpublic ConfigurationCustomizer configurationCustomizer(){return new ConfigurationCustomizer(){@Overridepublic void customize(Configuration configuration) {//开启驼峰命名,使实体属性和数据库字段能够对应上configuration.setMapUnderscoreToCamelCase(true);}};}
}
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><!--在mybatis全局配置文件中配置开启驼峰命名--><settings><setting name="mapUnderscoreToCamelCase" value="true"/></settings>
</configuration>
EmployeeMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.kejizhentan.springbootmybatisproject.mapper.EmployeeMapper"><select id="getEmpById" resultType="com.kejizhentan.springbootmybatisproject.bean.Employee">SELECT * FROM employee WHERE id=#{id}</select><insert id="insertEmp">INSERT INTO employee(lastName,email,gender,d_id) VALUES (#{lastName},#{email},#{gender},#{dId})</insert>
</mapper>
SpringbootMybatisProjectApplication.java
@MapperScan("com.kejizhentan.springbootmybatisproject.mapper")
@SpringBootApplication
public class SpringbootMybatisProjectApplication {public static void main(String[] args) {SpringApplication.run(SpringbootMybatisProjectApplication.class, args);}}
DeptController.java
@MapperScan("com.kejizhentan.springbootmybatisproject.mapper")
@SpringBootApplication
public class SpringbootMybatisProjectApplication {public static void main(String[] args) {SpringApplication.run(SpringbootMybatisProjectApplication.class, args);}
}
更多配置请参考:http://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/
2. SpringBoot整合SpringData JPA
⑴ SpringData简介
⑵ SpringBootr整合SpringData JPA的具体操作
创建项目
JPA:ORM(Object Relational Mapping);
1)、编写一个实体类(bean)和数据表进行映射,并且配置好映射关系;
//使用JPA注解配置映射关系
@Entity //告诉JPA这是一个实体类(和数据表映射的类)
@Table(name = "tbl_user") //@Table来指定和哪个数据表对应;如果省略默认表名就是user;
public class User {@Id //这是一个主键@GeneratedValue(strategy = GenerationType.IDENTITY)//自增主键private Integer id;@Column(name = "last_name",length = 50) //这是和数据表对应的一个列private String lastName;@Column //省略默认列名就是属性名private String email;. . .
}
2)、编写一个Dao接口来操作实体类对应的数据表(Repository)
// JpaRepository<User,Integer> 泛型1表示对应的实体,泛型2表示对应实体的主键类型
public interface UserRepository extends JpaRepository<User,Integer> {}
3)、基本的配置JpaProperties
# 更新或者创建数据表结构
spring.jpa.hibernate.ddl-auto=update
#控制台显示SQL
spring.jpa.properties.hibernate.show_sql=true
详细代码如下:
项目结构如下:
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.kejizhentan</groupId><artifactId>springboot-datajpa</artifactId><version>0.0.1-SNAPSHOT</version><name>springboot-datajpa</name><description>Demo project for Spring Boot</description><properties><java.version>1.8</java.version><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><spring-boot.version>2.3.7.RELEASE</spring-boot.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope><exclusions><exclusion><groupId>org.junit.vintage</groupId><artifactId>junit-vintage-engine</artifactId></exclusion></exclusions></dependency></dependencies><dependencyManagement><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-dependencies</artifactId><version>${spring-boot.version}</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement><build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.8.1</version><configuration><source>1.8</source><target>1.8</target><encoding>UTF-8</encoding></configuration></plugin><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><version>2.3.7.RELEASE</version><configuration><mainClass>com.kejizhentan.springbootdatajpa.SpringbootDatajpaApplication</mainClass></configuration><executions><execution><id>repackage</id><goals><goal>repackage</goal></goals></execution></executions></plugin></plugins></build>
</project>
User.java
package com.kejizhentan.springbootdatajpa.bean;
import javax.persistence.*;
//使用JPA注解配置映射关系
@Entity //告诉JPA这是一个实体类(和数据表映射的类)
@Table(name = "tbl_user") //@Table来指定和哪个数据表对应;如果省略默认表名就是user;
public class User {@Id //这是一个主键@GeneratedValue(strategy = GenerationType.IDENTITY)//自增主键private Integer id;@Column(name = "last_name",length = 50) //这是和数据表对应的一个列private String lastName;@Column //省略默认列名就是属性名private String email;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getLastName() {return lastName;}public void setLastName(String lastName) {this.lastName = lastName;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}
}
application.properties
# 应用名称
spring.application.name=springboot-datajpa
# 应用服务 WEB 访问端口
server.port=8080
# 数据库驱动:
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 数据源名称
spring.datasource.name=defaultDataSource
# 数据库连接地址
spring.datasource.url=jdbc:mysql://localhost:3306/kjzt?serverTimezone=UTC
# 数据库用户名&密码:
spring.datasource.username=root
spring.datasource.password=123456
# 更新或者创建数据表结构
spring.jpa.hibernate.ddl-auto=update
#控制台显示SQL
spring.jpa.properties.hibernate.show_sql=true
UserController.java
@RestController
public class UserController {@AutowiredUserRepository userRepository;@GetMapping("/user/{id}")public User getUser(@PathVariable("id") Integer id){User user = userRepository.getOne(id);return user;}@GetMapping("/user")public User insertUser(User user){User save = userRepository.save(user);return save;}
}
UserRepository.java
// JpaRepository<User,Integer> 泛型1表示对应的实体,泛型2表示对应实体的主键类型
public interface UserRepository extends JpaRepository<User,Integer> {
}
SpringbootDatajpaApplication.java
@SpringBootApplication
public class SpringbootDatajpaApplication {public static void main(String[] args) {SpringApplication.run(SpringbootDatajpaApplication.class, args);}}
六、流行框架介绍(SpringBoot框架详解(含底层原理介绍,适用于springBoot1.x和springBoot2.x,属于通用版本))相关推荐
- SpringSecurity权限管理框架系列(六)-Spring Security框架自定义配置类详解(二)之authorizeRequests配置详解
1.预置演示环境 这个演示环境继续沿用 SpringSecurit权限管理框架系列(五)-Spring Security框架自定义配置类详解(一)之formLogin配置详解的环境. 2.自定义配置类 ...
- Android Binder框架实现之bindService详解
Android Binder框架实现之bindService详解 Android Binder框架实现目录: Android Binder框架实现之Binder的设计思想 Android Bi ...
- 超轻量级DI容器框架Google Guice与Spring框架的区别教程详解及其demo代码片段分享...
超轻量级DI容器框架Google Guice与Spring框架的区别教程详解及其demo代码片段分享 DI框架 Google-Guice入门介绍 转载于:https://www.cnblogs.com ...
- androidentity什么用_Android ORM 框架:GreenDao 使用详解(进阶篇)
前言 在 Android ORM 框架:GreenDao 使用详解(基础篇) 中,我们了解了 GreenDao 的基本使用,本文我们将深入讲解 GreenDao 的使用 . 一.复杂表结构 a, 使用 ...
- Android Binder框架实现之Parcel详解之基本数据的读写
Android Binder框架实现之Parcel详解之基本数据的读写 Android Binder框架实现目录: Android Binder框架实现之Binder的设计思想 Android ...
- java集合框架史上最详解(list set 以及map)
title: Java集合框架史上最详解(list set 以及map) tags: 集合框架 list set map 文章目录 一.集合框架总体架构 1.1 集合框架在被设计时需满足的目标 1.2 ...
- 自动化测试框架[Cypress元素操作详解]
前提 已经熟练掌握了Cypress的基本知识,请参考自动化测试框架[Cypress概述]和自动化测试框架[各自动化测试框架比较] 已经熟练掌握Cypress环境配置,请参考自动化测试框架[Cypres ...
- java 线程同步的list_java集合框架线程同步代码详解
List接口的大小可变数组的实现.实现了所有可选列表操作,并允许包括null在内的所有元素.除了实现List接口外,此类还提供一些方法来操作内部用来存储列表的数组的大小.(此类大致上等同于Vector ...
- spring-boot注解详解(一)
spring-boot注解详解(一) @SpringBootApplication @SpringBootApplication = (默认属性)@Configuration + @EnableAut ...
- 【SpringBoot 】SpringBoot注解详解
[SpringBoot ]SpringBoot注解详解 一.注解(annotations)列表 @SpringBootApplication:包含了@ComponentScan.@Configura ...
最新文章
- SharePoint2010沙盒解决方案基础开发——关于TreeView树形控件读取列表数据(树形导航)的webpart开发及问题...
- 【 FPGA 】组合逻辑中的竞争与险象问题(三)
- 【长篇连载】桌面管理演义 第八回 电脑中毒很危险 告警隔离防传染
- Windows上安装Kafka需要注意的几点
- crontab 案例
- Eclipse下导入外部jar包的3种方式
- phpmyadmin登陆错误:The requested URL /phpmyadmin was not found on this serve
- 非常时期,手机不能没电不能离身啊
- memory java heap_java.lang.OutOfMemoryError: Java heap space解决方法
- Scrapy 发起post请求
- 《Head first HTML与CSS 第二版》读书笔记 第一章 了解HTML
- rtt segger 低功耗模式_Segger RTT使用注意事项
- 每个程序员都应该知道的事情
- 清蒸野猪佩奇自带LastDance
- 动态规划 自然数拆分
- 《路由器开发 - 路由器刷机指南》优酷路由宝 YK-L1刷机
- 新车磨合应该从正确启动发动机开始
- 微信开发网页授权获取用户信息
- python对excel某一列求和-如何对某一列自动分组,统计求和
- ubuntu-mysql的安装