Java学习笔记-全栈-web开发-20-SpringBoot核心技术

本节笔记参照雷丰阳老师的springboot教学视频


1. 微服务

微服务是2014,martin fowler 提出来的, 详细参照微服务文档

微服务:架构风格(服务微化)
一个应用应该是一组小型服务;可以通过HTTP的方式进行互通;

单体应用:ALL IN ONE

微服务:每一个功能元素最终都是一个可独立替换和独立升级的软件单元;

可以理解为,将各种模块单独作为一个project,通过maven进行各种project之间的互通。
详情参阅maven聚合

2. POM文件

2.1 父项目进行依赖管理

<parent> 
	<groupId>org.springframework.boot</groupId> 
	<artifactId>spring‐boot‐starter‐parent</artifactId> 
	<version>1.5.9.RELEASE</version> 
</parent> 
他的父项目是 
<parent> 
	<groupId>org.springframework.boot</groupId> 
	<artifactId>spring‐boot‐dependencies</artifactId> 
	<version>1.5.9.RELEASE</version> 
	<relativePath>../../spring‐boot‐dependencies</relativePath> 
</parent> 
他来真正管理Spring Boot应用里面的所有依赖版本; 

Spring Boot的版本仲裁中心;
以后我们导入依赖默认是不需要写版本;(没有在dependencies里面管理的依赖自然需要声明版本号)

2.2 启动器Starter

<dependency> 
	<groupId>org.springframework.boot</groupId> 
	<artifactId>spring‐boot‐starter‐web</artifactId> 
</dependency> 

spring-boot-starter-web:
spring-boot-starter:spring-boot场景启动器;帮我们导入了web模块正常运行所依赖的组件;
Spring Boot将所有的功能场景都抽取出来,做成一个个的starters(启动器),只需要在项目里面引入这些starter ,相关场景的所有依赖都会导入进来。
要用什么功能就导入什么场景的启动器 。

2.3. 插件

插件在plugins内,就是打成jar包的一些组件,通过“插件”的形式加入项目当中。

还可以百度了解“Springboot插件化开发”。

<build> 
	<plugins> 
		<plugin> 
			<groupId>org.springframework.boot</groupId> 
			<artifactId>spring‐boot‐maven‐plugin</artifactId> 
		</plugin> 
	</plugins> 
</build> 

这个用于将springboot打成jar包
如果未进行上述配置,应用本地可以正常启动,但是发布到测试机器就无法启动。

3. 主程序类,主入口类

以下内容涉及到进入注解中,都有代码展示,因此不多做说明

/**
* @SpringBootApplication 来标注一个主程序类,说明这是一个Spring Boot应用 
*/ 
@SpringBootApplication 
public class HelloWorldMainApplication { 

	public static void main(String[] args) { 
		// Spring应用启动起来 
		SpringApplication.run(HelloWorldMainApplication.class,args); 
	} 
} 

@SpringBootApplication:Spring Boot应用标注在某个类上说明这个类是SpringBoot的主配置类,SpringBoot 就应该运行这个类的main方法来启动SpringBoot应用;

@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 加入到bean容器,交给spring管理

@EnableAutoConfiguration:开启自动配置功能;
以前我们需要配置的东西,Spring Boot帮我们自动配置;@EnableAutoConfiguration告诉SpringBoot开启自动配置功能;这样自动配置才能生效;

@AutoConfigurationPackage 
@Import(EnableAutoConfigurationImportSelector.class) 
public @interface EnableAutoConfiguration { 

@AutoConfigurationPackage:自动配置包

@Import(AutoConfigurationPackages.Registrar.class): Spring的底层注解@Import,给容器中导入一个组件;导入的组件由
AutoConfigurationPackages.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-x.x.x.RELEASE.jar;

4. 配置文件

SpringBoot使用一个全局的配置文件,配置文件名是固定的;

  • application.properties
  • application.yml

配置文件的作用:
修改SpringBoot自动配置的默认值;SpringBoot在底层都给我们自动配置好;

YAML(YAML Ain’t Markup Language)
YAML A Markup Language:是一个标记语言
YAML isn’t Markup Language:不是一个标记语言;

标记语言:
以前的配置文件;大多都使用的是 xxxx.xml文件;
YAML:以数据为中心,比json、xml等更适合做配置文件;

在这里插入图片描述

4.1 YAML语法

基本语法
k:(空格)v:表示一对键值对(空格必须有);
以空格的缩进来控制层级关系;只要是左对齐的一列数据,都是同一个层级的
在这里插入图片描述

值的写法
字面量:普通的值(数字,字符串,布尔)
k: v:字面直接来写;

字符串默认不用加上单引号或者双引号;

“”:双引号;不会转义字符串里面的特殊字符;特殊字符会作为本身想表示的意思
name: “zhangsan \n lisi”:输出;zhangsan 换行 lisi
‘’:单引号;会转义特殊字符,特殊字符最终只是一个普通的字符串数据
name: ‘zhangsan \n lisi’:输出;zhangsan \n lisi

对象、Map(属性和值)(键值对):
k: v:在下一行来写对象的属性和值的关系;注意缩进
对象还是k: v的方式

friends:
	lastName: zs
	age: 20

行内写法:

friends: {lastName: zs,age: 18}

数组(List、Set)
用-表示数组中的一个元素

pets:
 - cat
 - dog
 - pig

行内写法:

pets: {cat,dog,pig}

4.2 配置文件值注入

配置文件

person: 
	lastName: hello 
	age: 18 
	boss: false 
	birth: 2017/12/12 
	maps: {k1: v1,k2: 12} 
	lists: 
		‐ lisi 
		‐ zhaoliu 
	dog:
		name: 小狗 
		age: 12 

javabean

/**
* 将配置文件中配置的每一个属性的值,映射到这个组件中 
* @ConfigurationProperties:告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定; 
* prefix = "person":配置文件中哪个下面的所有属性进行一一映射 
*
* 只有这个组件是容器中的组件,才能容器提供的@ConfigurationProperties功能; 
*
*/ 
@Component 
@ConfigurationProperties(prefix = "person") 
public class Person { 
	private String lastName; 
	private Integer age; 
	private Boolean boss; 
	private Date birth; 
	private Map<String,Object> maps; 
	private List<Object> lists; 
	private Dog dog; 

我们可以导入配置文件处理器,以后编写配置就有提示了

<!‐‐导入配置文件处理器,配置文件进行绑定就会有提示‐‐> 
<dependency> 
	<groupId>org.springframework.boot</groupId> 
	<artifactId>spring‐boot‐configuration‐processor</artifactId> 
	<optional>true</optional> 
</dependency> 

properties配置文件在idea中默认utf-8可能会乱码

在这里插入图片描述


@Value获取值和@ConfigurationProperties获取值比较
在这里插入图片描述配置文件yml还是properties他们都能获取到值;

  • 如果说,我们只是在某个业务逻辑中需要获取一下配置文件中的某项值,使用@Value;
  • 如果说,我们专门编写了一个javaBean来和配置文件进行映射,我们就直接使用@ConfigurationProperties;

4.3 配置文件注入值校验

@Component 
@ConfigurationProperties(prefix = "person") 
@Validated 
public class Person { 
/**
* <bean class="Person"> 
* <property name="lastName" value="字面量/${key}从环境变量、配置文件中获取值/# 
{SpEL}"></property> 
* <bean/> 
*/ 
	//lastName必须是邮箱格式 
	@Email 
	//@Value("${person.last‐name}") 
	private String lastName; 
	//@Value("#{11*2}") 
	private Integer age; 
	//@Value("true") 
	private Boolean boss; 
	private Date birth; 
	private Map<String,Object> maps; 
	private List<Object> lists; 
	private Dog dog;

4.4 配置文件占位符

随机数写法

${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

4.5 导入自定义配置文件

通过 @PropertySource&@ImportResource&@Bean

@PropertySource:加载指定的配置文件


/**
* 将配置文件中配置的每一个属性的值,映射到这个组件中 
* @ConfigurationProperties:告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定; 
* prefix = "person":配置文件中哪个下面的所有属性进行一一映射 
*
* 只有这个组件是容器中的组件,才能容器提供的@ConfigurationProperties功能; 
* @ConfigurationProperties(prefix = "person")默认从全局配置文件中获取值; 
*
*/ 
@PropertySource(value = {"classpath:person.properties"}) 
@Component 
@ConfigurationProperties(prefix = "person") 
//@Validated
public class Person { 
/**
* <bean class="Person"> 
* <property name="lastName" value="字面量/${key}从环境变量、配置文件中获取值/# 
{SpEL}"></property> 
* <bean/> 
*/ 
	//lastName必须是邮箱格式 
	// @Email 
	//@Value("${person.last‐name}") 
	private String lastName; 
	//@Value("#{11*2}") 
	private Integer age; 
	//@Value("true") 
	private Boolean boss; 

@ImportResource:导入Spring的配置文件,让配置文件里面的内容生效

Spring Boot里面没有Spring的配置文件,我们自己编写的配置文件,也不能自动识别;
想让Spring的配置文件生效,需要通过@ImportResource加载进来;
@ImportResource标注在一个配置类上

@ImportResource(locations = {"classpath:beans.xml"}) 
导入Spring的配置文件让其生效 

如果通过编写Spring的配置文件加载配置,需要写下面的xml

<?xml version="1.0" encoding="UTF‐8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema‐instance" 
xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring‐beans.xsd"> 
<bean id="helloService" class="com.atguigu.springboot.service.HelloService"></bean> 
</beans>

但是,SpringBoot推荐给容器中添加组件的方式是:使用全注解的方式

  • 1 配置类@Configuration------>Spring配置文件
  • 2 使用@Bean给容器中添加组件

如:

/**
* @Configuration:指明当前类是一个配置类;就是来替代之前的Spring配置文件 
* 
* 在配置文件中用<bean><bean/>标签添加组件 
*
*/ 
@Configuration 
public class MyAppConfig { 
	//将方法的返回值添加到容器中;容器中这个组件默认的id就是方法名 
	@Bean 
	public HelloService helloService02(){ 
	System.out.println("配置类@Bean给容器中添加组件了..."); 
	return new HelloService(); 
	} 
}

4.6 profile

多Profile文件

我们在主配置文件编写的时候,文件名可以是 application-{profile}.properties/yml
默认使用application.properties的配置;

yml多文档块方式

server: 
	port: 8081 
spring: 
	profiles: 
		active: prod 
‐‐‐ 
server: 
	port: 8083 
spring: 
	profiles: dev 
‐‐‐ 
server: 
	port: 8084 
spring: 
	profiles: prod #指定属于哪个环境

激活指定profile

  • 1、在配置文件中指定 spring.profiles.active=dev
  • 2、命令行:
    java -jar spring-boot-02-config-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev;
    可以直接在测试的时候,配置传入命令行参数
  • 3、虚拟机参数;
    -Dspring.profiles.active=dev

小结
1.运维配置更改
(1)Yml中profile分块配置多环境配置项,然后在命令行中执行配置块
(2)Jar包同级目录下的配置文件会被加载
(3)所有配置都是“互补配置”模式,按优先级覆盖。

4.7 配置文件加载位置

springboot 启动会扫描以下位置的application.properties或者application.yml文件作为Spring boot的默认配置文件

  • –file:./config/
  • –file:./
  • –classpath:/config/
  • –classpath:/

优先级由高到底,高优先级的配置会覆盖低优先级的配置;
SpringBoot会从这四个位置全部加载主配置文件,进行互补配置(对于同一个配置项,高优先级的覆盖低优先级的,对于不同配置项,所有配置文件都生效)

我们还可以通过spring.config.location来改变默认的配置文件位置 :
项目打包好以后,我们可以使用命令行参数的形式,启动项目的时候来指定配置文件的新位置;指定配置文件和默认加载的这些配置文件共同起作用形成互补配置;

java -jar TestProject.jar --spring.config.location=G:/application.properties

(将本地的G:/application.properties作为TestProject的默认配置文件)

4.8 外部配置文件加载顺序

SpringBoot也可以从以下位置加载配置; 优先级从高到低;高优先级的配置覆盖低优先级的配置,所有的配置会 形成互补配置

1.命令行参数
所有的配置都可以在命令行上进行指定
java -jar TestPorject.jar --server.port=8087 --server.context-path=/abc
多个配置用空格分开; --配置项=值

2.来自java:comp/env的JNDI属性
3.Java系统属性(System.getProperties())
4.操作系统环境变量
5.RandomValuePropertySource配置的random.*属性值

由jar包外向jar包内进行寻找;
优先加载带profile的

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

再来加载不带profile的

8.jar包外部的application.properties或application.yml(不带spring.profile)配置文件
9.jar包内部的application.properties或application.yml(不带spring.profile)配置文件
10.@Configuration注解类上的@PropertySource
11.通过SpringApplication.setDefaultProperties指定的默认属性

所有支持的配置加载来源:参考官方文档

5. 自动配置原理

配置文件能写什么,可以参考官方文档

每次都查阅官方文档,其实挺麻烦。因此,自然有更好的办法。

我们先看看自动配置原理。

5.1 原理概述

1、SpringBoot启动的时候加载主配置类,开启了自动配置功能@EnableAutoConfiguration

2、@EnableAutoConfiguration 作用:

  • 利用EnableAutoConfigurationImportSelector给容器中导入一些组件
  • 可以查看selectImports()方法的内容;
  • List configurations = getCandidateConfigurations(annotationMetadata, attributes);获取候选的配置

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

在这里插入图片描述
每一个这样的 xxxAutoConfiguration类都是容器中的一个组件,都加入到容器中,用他们来做自动配置;

3、每一个自动配置类进行自动配置功能;

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

//声明为配置类,proxyBeanMethods = false表明使用jdk动态代理
@Configuration( 
    proxyBeanMethods = false
)  
//启动指定类的ConfigurationProperties功能,将配置文件中对应的值和HttpEncodingProperties绑定,并将HttpEncodingProperties加入到ioc容器中
@EnableConfigurationProperties({HttpProperties.class}) 
//判断当前是否为web应用,如果是,则配置生效
@ConditionalOnWebApplication(
    type = Type.SERVLET
)
//判断当前项目是否有这个类
@ConditionalOnClass({CharacterEncodingFilter.class})
//判断当前是否存在这个配置
//value={"enabled"},mathcIfMissing=true  如果enabled不存在,则让它赋值为true
@ConditionalOnProperty(
    prefix = "spring.http.encoding",
    value = {"enabled"},
    matchIfMissing = true
)
public class HttpEncodingAutoConfiguration {
    private final Encoding properties;

	//只有一个有参构造器的情况下,参数的值就会从容器中拿
    public HttpEncodingAutoConfiguration(HttpProperties properties) {
        this.properties = properties.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.autoconfigure.http.HttpProperties.Encoding.Type.REQUEST));
        filter.setForceResponseEncoding(this.properties.shouldForce(org.springframework.boot.autoconfigure.http.HttpProperties.Encoding.Type.RESPONSE));
        return filter;
    }

根据当前不同的条件判断,决定这个配置类是否生效。
一但这个配置类生效;这个配置类就会给容器中添加各种组件;这些组件的属性是从对应的properties类中获取的,这些类里面的每一个属性又是和配置文件绑定的;

5、所有在配置文件中能配置的属性都是在xxxxProperties类中封装着;配置文件能配置什么就可以参照某个功能对应的这个属性类 (因此不需要查官方文档)

精髓:
1)、SpringBoot启动会加载大量的自动配置类
2)、首先看我们需要的功能有没有SpringBoot默认写好的自动配置类;
3)、再来看这个自动配置类中到底配置了哪些组件(只要我们要用的组件有,则不需要再配置了)
4)、给容器中自动配置类添加组件的时候,会从properties类中获取某些属性。我们可以在配置文件中指定这些属性的值;

xxxxAutoConfigurartion:自动配置类;
给容器中添加组件
xxxxProperties:封装配置文件中相关属性;

5.2 细节

5.2.1 Conditional派生注解

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

@Conditional扩展注解作用(判断是否满足当前指定条件)
@ConditionalOnJava系统的java版本是否符合要求
@ConditionalOnBean容器中存在指定Bean;
@ConditionalOnMissingBean容器中不存在指定Bean;
@ConditionalOnExpression满足SpEL表达式指定
@ConditionalOnClass系统中有指定的类
@ConditionalOnMissingClass系统中没有指定的类
@ConditionalOnSingleCandidate容器中只有一个指定的Bean,或者这个Bean是首选Bean
@ConditionalOnProperty系统中指定的属性是否有指定的值
@ConditionalOnResource类路径下是否存在指定资源文件
@ConditionalOnWebApplication当前是web环境
@ConditionalOnNotWebApplication当前不是web环境
@ConditionalOnJndiJNDI存在指定项

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

可以通过启用 debug=true属性;来让控制台打印自动配置报告,这样我们就可以很方便的知道哪些自动配置类生效;

========================= 
AUTO‐CONFIGURATION REPORT 
========================= 
Positive matches:(自动配置类启用的) 
‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 
DispatcherServletAutoConfiguration matched:@ConditionalOnClass found required class 
'org.springframework.web.servlet.DispatcherServlet'; @ConditionalOnMissingClass did not find 
unwanted class (OnClassCondition)@ConditionalOnWebApplication (required) found StandardServletEnvironment 
(OnWebApplicationCondition) 

Negative matches:(没有启动,没有匹配成功的自动配置类) 
‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 
ActiveMQAutoConfiguration: 
Did not match:@ConditionalOnClass did not find required classes 'javax.jms.ConnectionFactory', 
'org.apache.activemq.ActiveMQConnectionFactory' (OnClassCondition) 
AopAutoConfiguration: 
Did not match:@ConditionalOnClass did not find required classes 
'org.aspectj.lang.annotation.Aspect', 'org.aspectj.lang.reflect.Advice' (OnClassCondition) 

6. 日志

日志门面日志实现
JCL、SLF4J、jboss-loggingLog4j、JUL、Log4j2、Logback

左边选一个门面,右边选一个实现。

Springboot默认使用的是SLF4j和logback。

开发的时候,日志记录方法的调用,不应该直接调用日志的实现类,而是调用日志抽象层的方法。这样,如果更改了日志实现,也不影响原有代码。


如何让系统中所有的日志都统一到slf4j;
1、将系统中其他日志框架先排除出去;
2、用中间包来替换原有的日志框架;
3、我们导入slf4j其他的实现


SpringBoot能自动适配所有的日志,而且底层使用slf4j+logback的方式记录日志,引入其他框架的时候,只需要把这个框架依赖的日志框架排除掉即可。

7. Springboot Web开发技术

7.1 使用流程

使用SpringBoot的流程;
1)、创建SpringBoot应用,选中我们需要的模块
2)、SpringBoot已经默认将这些场景配置好了,只需要在配置文件中指定少量配置就可以运行起来
3)、自己编写业务代码

疑问:Springboot自动配置了很多东西,那么当前场景SpringBoot帮我们配置了什么?能不能修改?能修改哪些配置?能不能扩展?…

xxxxAutoConfiguration:帮我们给容器中自动配置组件
xxxxProperties:配置类来封装配置文件的内容

7.2 静态资源的映射规则

@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false) 
public class ResourceProperties implements ResourceLoaderAware { 
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};
//可以设置和静态资源有关的参数,缓存时间等 

WebMvcAuotConfiguration

@Override 
public void addResourceHandlers(ResourceHandlerRegistry registry) { 
	if (!this.resourceProperties.isAddMappings()) { 
		logger.debug("Default resource handling disabled"); 
		return; 
	}
	Integer cachePeriod = this.resourceProperties.getCachePeriod(); 
	if (!registry.hasMappingForPattern("/webjars/**")) { 
		customizeResourceHandlerRegistration( 
		registry.addResourceHandler("/webjars/**") 
		.addResourceLocations( 
		"classpath:/META‐INF/resources/webjars/") 
		.setCachePeriod(cachePeriod)); 
	}
	String staticPathPattern = this.mvcProperties.getStaticPathPattern(); 
	//静态资源文件夹映射 
	if (!registry.hasMappingForPattern(staticPathPattern)) { 
		customizeResourceHandlerRegistration( 
		registry.addResourceHandler(staticPathPattern) 
		.addResourceLocations( 
		this.resourceProperties.getStaticLocations()) 
		.setCachePeriod(cachePeriod)); 
	} 
}

//配置欢迎页映射 
@Bean 
public WelcomePageHandlerMapping welcomePageHandlerMapping( 
	ResourceProperties resourceProperties) { 
		return new WelcomePageHandlerMapping(resourceProperties.getWelcomePage(), 
		this.mvcProperties.getStaticPathPattern()); 
	}

	//配置喜欢的图标 
	@Configuration 
	@ConditionalOnProperty(value = "spring.mvc.favicon.enabled", matchIfMissing = true) 
	public static class FaviconConfiguration { 
	private final ResourceProperties resourceProperties; 
	public FaviconConfiguration(ResourceProperties resourceProperties) { 
		this.resourceProperties = resourceProperties; 
	}
	@Bean 
	public SimpleUrlHandlerMapping faviconHandlerMapping() { 
		SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping(); 
		mapping.setOrder(Ordered.HIGHEST_PRECEDENCE + 1); 
		//所有 **/favicon.ico 
		mapping.setUrlMap(Collections.singletonMap("**/favicon.ico", 
faviconRequestHandler())); 
		return mapping; 
	}
	
	@Bean 
	public ResourceHttpRequestHandler faviconRequestHandler() { 
		ResourceHttpRequestHandler requestHandler = new 
		ResourceHttpRequestHandler(); 
		requestHandler 
		.setLocations(this.resourceProperties.getFaviconLocations()); 
		return requestHandler; 
	} 
} 

从上面的源码可以看到

  • 静态资源的默认路径有:{“classpath:/META-INF/resources/”, “classpath:/resources/”, “classpath:/static/”, “classpath:/public/”};
  • 所有 /webjars/** ,都去 classpath:/META-INF/resources/webjars/ 找资源
  • 在静态资源路径下创建**/favicon.ico,会成为网页图标

webjars:以jar包的方式引入静态资源
webjars引用方式查询

在这里插入图片描述
可以通过这种方式访问静态资源
localhost:8080/webjars/jquery/3.3.1/jquery.js

<!‐‐引入jquery‐webjar‐‐>在访问的时候只需要写webjars下面资源的名称即可 
<dependency> 
	<groupId>org.webjars</groupId> 
	<artifactId>jquery</artifactId> 
	<version>3.3.1</version> 
</dependency> 

小结

静态资源的访问
在我们开发Web应用的时候,需要引用大量的js、css、图片等静态资源。
Spring Boot默认提供静态资源目录位置需置于classpath下,目录名需符合如下规则:
/static
/public
/resources
/META-INF/resources

举例:我们可以在src/main/resources/目录下创建static,在该位置放置一个图片文件。启动程序后,尝试访问http://localhost:8080/imgs/d.jpg。如能显示图片,配置成功。

可以通过以下方式进行更改:

spring.mvc.static-path-pattern: /static/**

配置后优点:好像没发现???
配置后缺点:访问静态资源文件要加static才行,(未配置时不用加static作为前缀亦可进行正常访问静态资源)

/* 表示所有的文件夹,但不包含子文件夹
/** 是表示所有的文件夹及里面的子文件夹

7.3 模板引擎 thymeleaf

Springboot推荐使用thymeleaf
在这里插入图片描述
模板引擎的作用:通过在html中写模板引擎代码,引入java控制器中存储的数据,然后渲染包含数据的页面给前端。

7.3.1 使用模板引擎

只要我们把HTML页面放在classpath:/templates/,thymeleaf就能自动渲染;

步骤:
1、导入thymeleaf的名称空间

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

2、使用thymeleaf语法;

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

7.3.2 语法规则

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

下图通过与jsp进行对比学习
在这里插入图片描述
th:任意html属性;来替换原生属性的值

2)、表达式

Simple expressions:(表达式语法) 
	Variable Expressions: ${...}:获取变量值;OGNL; 
		1)、获取对象的属性、调用方法 
		2)、使用内置的基本对象: 
			#ctx : the context object. 
			#vars: the context variables. 
			#locale : the context locale. 
			#request : (only in Web Contexts) the HttpServletRequest object. 
			#response : (only in Web Contexts) the HttpServletResponse object. 
			#session : (only in Web Contexts) the HttpSession object. 
			#servletContext : (only in Web Contexts) the ServletContext object. 
			${session.foo} 
		3)、内置的一些工具对象: 
			#execInfo : information about the template being processed. 
			#messages : methods for obtaining externalized messages inside variables expressions, in the same way as they would be obtained using #{…} syntax. 
			#uris : methods for escaping parts of URLs/URIs 
			#conversions : methods for executing the configured conversion service (if any). 
			#dates : methods for java.util.Date objects: formatting, component extraction, etc. 
			#calendars : analogous to #dates , but for java.util.Calendar objects. 
			#numbers : methods for formatting numeric objects. 
			#strings : methods for String objects: contains, startsWith, prepending/appending, etc. 
			#objects : methods for objects in general. 
			#bools : methods for boolean evaluation. 
			#arrays : methods for arrays. 
			#lists : methods for lists. 
			#sets : methods for sets. 
			#maps : methods for maps. 
			#aggregates : methods for creating aggregates on arrays or collections. 
			#ids : methods for dealing with id attributes that might be repeated (for example, as a result of an iteration). 
			
			Selection Variable Expressions: *{...}:选择表达式:和${}在功能上是一样; 
			补充:配合 th:object="${session.user}: 
				<div th:object="${session.user}"> 
					<p>Name: <span th:text="*{firstName}">Sebastian</span>.</p> 
					<p>Surname: <span th:text="*{lastName}">Pepper</span>.</p> 
					<p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p> 
				</div> 
			
			Message Expressions: #{...}:获取国际化内容 
			Link URL Expressions: @{...}:定义URL; 
				@{/order/process(execId=${execId},execType='FAST')} 
			Fragment Expressions: ~{...}:片段引用表达式 
				<div th:insert="~{commons :: main}">...</div> 
			
			Literals(字面量) 
				Text literals: 'one text' , 'Another one!' ,… 
				Number literals: 0 , 34 , 3.0 , 12.3 ,… 
				Boolean literals: true , false 
				Null literal: null 
				Literal tokens: one , sometext , main ,… 
			
			Text operations:(文本操作) 
				String concatenation: + 
				Literal substitutions: |The name is ${name}| 
			
			Arithmetic operations:(数学运算) 
				Binary operators: + , ‐ , * , / , %
				Minus sign (unary operator): ‐ 
			
			Boolean operations:(布尔运算) 
				Binary operators: and , or 
				Boolean negation (unary operator): ! , not 
			
			Comparisons and equality:(比较运算) 
				Comparators: > , < , >= , <= ( gt , lt , ge , le ) 
				Equality operators: == , != ( eq , ne ) 

			Conditional operators:条件运算(三元运算符) 
				If‐then: (if) ? (then) 
				If‐then‐else: (if) ? (then) : (else) 
				Default: (value) ?: (defaultvalue) 
			
			Special tokens: 
				No‐Operation: _

如果使用$未找到 ==》用src引入js

8. SpringMVC自动配置

查看相关文档

8.1 SpringMVC auto-configuration

Spring Boot 自动配置好了SpringMVC

以下是SpringBoot对SpringMVC的默认配置:(WebMvcAutoConfiguration)

  • Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans.

    • 自动配置了ViewResolver(视图解析器:根据方法的返回值得到视图对象(View),视图对象决定如何
      渲染(转发?重定向?))
    • ContentNegotiatingViewResolver:组合所有的视图解析器的;
    • 如何定制:我们可以自己给容器中添加一个视图解析器;自动的将其组合进来;
  • Support for serving static resources, including support for WebJars (see below).静态资源文件夹路
    径,webjars

    • Static index.html support. 静态首页访问
    • Custom Favicon support (see below). favicon.ico
  • 自动注册了 Converter , GenericConverter , Formatter beans.

    • Converter:转换器; public String hello(User user):类型转换使用Converter
    • Formatter 格式化器; 2019.12.17===Date;
@Bean 
@ConditionalOnProperty(prefix = "spring.mvc", name = "date‐format")//在文件中配置日期格式化的规则
public Formatter<Date> dateFormatter() { 
	return new DateFormatter(this.mvcProperties.getDateFormat());//日期格式化组件 
}

自己添加的格式化器转换器,我们只需要放在容器中即可

  • Support for HttpMessageConverters (see below)
    • HttpMessageConverter:SpringMVC用来转换Http请求和响应的;User—Json;
    • HttpMessageConverters 是从容器中确定;获取所有的HttpMessageConverter;

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

  • Automatic registration of MessageCodesResolver (see below).定义错误代码生成规则
    Automatic use of a ConfigurableWebBindingInitializer bean (see below).

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

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

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

  1. If you want to keep Spring Boot MVC features, and you just want to add additional MVC configuration (interceptors, formatters, view controllers etc.)
    you can add your own @Configuration class of type WebMvcConfigurerAdapter , but without @EnableWebMvc .

  2. If you wish to provide custom instances of
    RequestMappingHandlerMapping , RequestMappingHandlerAdapter or ExceptionHandlerExceptionResolver , you can declare a WebMvcRegistrationsAdapter instance providing such components.

  3. If you want to take complete control of Spring MVC, you can add your own @Configuration annotated with @EnableWebMvc .

8.2 扩展SpringMVC

<mvc:view‐controller path="/hello" view‐name="success"/> 
<mvc:interceptors> 
	<mvc:interceptor> 
		<mvc:mapping path="/hello"/> 
		<bean></bean> 
	</mvc:interceptor> 
</mvc:interceptors> 

编写一个配置类(@Configuration),是WebMvcConfigurerAdapter类型;不能标注@EnableWebMvc;
既保留了所有的自动配置,也能用我们扩展的配置;

//使用WebMvcConfigurerAdapter可以来扩展SpringMVC的功能 
@Configuration 
public class MyMvcConfig implements WebMvcConfigurer  { 
	@Override 
	public void addViewControllers(ViewControllerRegistry registry) { 
		// super.addViewControllers(registry); 
		//浏览器发送 /test请求来到 success 
		registry.addViewController("/test").setViewName("success"); 
	} 
}

原理:
1)、WebMvcAutoConfiguration是SpringMVC的自动配置类
2)、在做其他自动配置时会导入;@Import(EnableWebMvcConfiguration.class)

@Configuration 
public static class EnableWebMvcConfiguration extends DelegatingWebMvcConfiguration { 
	private final WebMvcConfigurerComposite configurers = new WebMvcConfigurerComposite(); 
	//从容器中获取所有的WebMvcConfigurer 
	@Autowired(required = false) 
	public void setConfigurers(List<WebMvcConfigurer> configurers) { 
		if (!CollectionUtils.isEmpty(configurers)) 
			this.configurers.addWebMvcConfigurers(configurers); 
			//一个参考实现;将所有的WebMvcConfigurer相关配置都来一起调用; 	
		@Override 
		// public void addViewControllers(ViewControllerRegistry registry) { 
			// for (WebMvcConfigurer delegate : this.delegates) { 
				// delegate.addViewControllers(registry); 
			// } 
		// } 
	}
} 

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

8.3 全面接管SpringMVC

全面接管:SpringBoot对SpringMVC的自动配置不需要了,所有都由我们自己配置。
只需要在配置类中添加@EnableWebMvc即可;

//使用WebMvcConfigurerAdapter可以来扩展SpringMVC的功能 
@EnableWebMvc 
@Configuration 
public class MyMvcConfig extends WebMvcConfigurerAdapter { 
	@Override 
	public void addViewControllers(ViewControllerRegistry registry) { 
	// super.addViewControllers(registry); 
	//浏览器发送 /atguigu 请求来到 success 
	registry.addViewController("/atguigu").setViewName("success"); 
	} 
} 

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

@EnableWebMvc将WebMvcConfigurationSupport组件导入进来;
而WebMvcConfigurationSupport不存在,自动配置才生效
导入的WebMvcConfigurationSupport只具备SpringMVC最基本的功能;


小结
1)、SpringBoot在自动配置很多组件的时候,先看容器中有没有用户自己配置的(@Bean、@Component)如果有,就用用户配置的,如果没有,才自动配置;如果有些组件可以有多个(ViewResolver)则将用户配置的和默认的组合起来;

2)、在SpringBoot中会有非常多的xxxConfigurer帮助我们进行扩展配置

3)、在SpringBoot中会有很多的xxxCustomizer帮助我们进行定制配置

8.4 定制错误页面

错误异常页面定制

  • (1)页面定制
    • ①有模板引擎的时候在templates中增加error/xxx.html即可
    • ②无模板引擎则将error/xxx.html放在static中
  • (2)Json数据定制
    • ①继承defaultErrorAttributes,重写getErrorAttributes
//给容器中加入我们自己定义的ErrorAttributes 
@Component 
public class MyErrorAttributes extends DefaultErrorAttributes { 
	@Override 
	public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) { 
		Map<String, Object> map = super.getErrorAttributes(requestAttributes, includeStackTrace); 
		map.put("company","atguigu"); 
		return map; 
	} 
} 

  • (3)统一返回数据(最好别用??)
@ControllerAdvice
public class MyExceptionHandler {
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public Map<String,Object> handleException(Exception e, HttpServletRequest request, HttpServletResponse response){
        Map<String,Object> map = new HashMap<>();
        map.put("code",500);
        map.put("message",e.toString());
        map.put("dep",e.getStackTrace()[0]);
        return map;
    }
}

8.5 servlet三大组件

在这里插入图片描述

//注册三大组件 
@Bean 
public ServletRegistrationBean myServlet(){ 
	ServletRegistrationBean registrationBean = new ServletRegistrationBean(new 
	MyServlet(),"/myServlet"); 
	return registrationBean; 
} 
@Bean 
public FilterRegistrationBean myFilter(){ 
	FilterRegistrationBean registrationBean = new FilterRegistrationBean(); 
	registrationBean.setFilter(new MyFilter()); 
	registrationBean.setUrlPatterns(Arrays.asList("/hello","/myServlet")); 
	return registrationBean; 
}
@Bean 
public ServletListenerRegistrationBean myListener(){ 
	ServletListenerRegistrationBean<MyListener> registrationBean = new 
	ServletListenerRegistrationBean<>(new MyListener()); 
	return registrationBean; 
}

9. SpringBoot中事务原理

声明式事务:
给方法上标注 @Transactional 表示当前方法是一个事务方法;

@EnableTransactionManagement 开启基于注解的事务管理功能;

配置事务管理器来控制事务;
@Bean
public PlatformTransactionManager transactionManager()

原理:
1)、@EnableTransactionManagement
利用TransactionManagementConfigurationSelector给容器中会导入组件

导入两个组件

  • AutoProxyRegistrar
  • P-roxyTransactionManagementConfiguration

2)、AutoProxyRegistrar:
给容器中注册一个 InfrastructureAdvisorAutoProxyCreator 组件;
nfrastructureAdvisorAutoProxyCreator:?
利用后置处理器机制在对象创建以后,包装对象,返回一个代理对象(增强器),代理对象执行方法利用拦截器链进行调用;

3)、ProxyTransactionManagementConfiguration 做了什么?
给容器中注册事务增强器;

  • 1)、事务增强器要用事务注解的信息,AnnotationTransactionAttributeSource解析事务注解
  • 2)、事务拦截器:
    • TransactionInterceptor;保存了事务属性信息,事务管理器;
    • 他是一个 MethodInterceptor;
    • 在目标方法执行的时候;
      • 执行拦截器链;
      • 事务拦截器:
        • 1)、先获取事务相关的属性
        • 2)、再获取PlatformTransactionManager,如果事先没有添加指定任何transactionmanger
          最终会从容器中按照类型获取一个PlatformTransactionManager;
        • 3)、执行目标方法
          如果异常,获取到事务管理器,利用事务管理回滚操作;
          如果正常,利用事务管理器,提交事务

10. SpringBoot中AOP原理

AOP原理:【看给容器中注册了什么组件,这个组件什么时候工作,这个组件的功能是什么?】
@EnableAspectJAutoProxy;

1、@EnableAspectJAutoProxy是什么?
@Import(AspectJAutoProxyRegistrar.class):给容器中导入AspectJAutoProxyRegistrar
利用AspectJAutoProxyRegistrar自定义给容器中注册bean;BeanDefinetion
internalAutoProxyCreator=AnnotationAwareAspectJAutoProxyCreator

给容器中注册一个AnnotationAwareAspectJAutoProxyCreator;

2、 AnnotationAwareAspectJAutoProxyCreator:
AnnotationAwareAspectJAutoProxyCreator
—>AspectJAwareAdvisorAutoProxyCreator
—>AbstractAdvisorAutoProxyCreator
—>AbstractAutoProxyCreator
implements SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware
关注后置处理器(在bean初始化完成前后做事情)、自动装配BeanFactory

AbstractAutoProxyCreator.setBeanFactory()
AbstractAutoProxyCreator.有后置处理器的逻辑;

AbstractAdvisorAutoProxyCreator.setBeanFactory()-》initBeanFactory()

AnnotationAwareAspectJAutoProxyCreator.initBeanFactory()

流程:
1)、传入配置类,创建ioc容器
2)、注册配置类,调用refresh()刷新容器;
3)、registerBeanPostProcessors(beanFactory);注册bean的后置处理器来方便拦截bean的创建;

  • 1)、先获取ioc容器已经定义了的需要创建对象的所有BeanPostProcessor
  • 2)、给容器中加别的BeanPostProcessor
  • 3)、优先注册实现了PriorityOrdered接口的BeanPostProcessor;
  • 4)、再给容器中注册实现了Ordered接口的BeanPostProcessor;
  • 5)、注册没实现优先级接口的BeanPostProcessor;
  • 6)、注册BeanPostProcessor,实际上就是创建BeanPostProcessor对象,保存在容器中;
    创建internalAutoProxyCreator的BeanPostProcessor【AnnotationAwareAspectJAutoProxyCreator】
    • 1)、创建Bean的实例
    • 2)、populateBean;给bean的各种属性赋值
    • 3)、initializeBean:初始化bean;
      • 1)、invokeAwareMethods():处理Aware接口的方法回调
      • 2)、applyBeanPostProcessorsBeforeInitialization():应用后置处理器的postProcessBeforeInitialization()
      • 3)、invokeInitMethods();执行自定义的初始化方法
      • 4)、applyBeanPostProcessorsAfterInitialization();执行后置处理器的postProcessAfterInitialization();
    • 4)、BeanPostProcessor(AnnotationAwareAspectJAutoProxyCreator)创建成功;–》aspectJAdvisorsBuilder
  • 7)、把BeanPostProcessor注册到BeanFactory中;
    beanFactory.addBeanPostProcessor(postProcessor);
    =以上是创建和注册AnnotationAwareAspectJAutoProxyCreator的过程==

AnnotationAwareAspectJAutoProxyCreator => InstantiationAwareBeanPostProcessor
4)、finishBeanFactoryInitialization(beanFactory);完成BeanFactory初始化工作;创建剩下的单实例bean
1)、遍历获取容器中所有的Bean,依次创建对象getBean(beanName);
getBean->doGetBean()->getSingleton()->
2)、创建bean
【AnnotationAwareAspectJAutoProxyCreator在所有bean创建之前会有一个拦截,InstantiationAwareBeanPostProcessor,会调用postProcessBeforeInstantiation()】
1)、先从缓存中获取当前bean,如果能获取到,说明bean是之前被创建过的,直接使用,否则再创建;
*只要创建好的Bean都会被缓存起来
2)、createBean();创建bean;
AnnotationAwareAspectJAutoProxyCreator 会在任何bean创建之前先尝试返回bean的实例
【BeanPostProcessor是在Bean对象创建完成初始化前后调用的】
【InstantiationAwareBeanPostProcessor是在创建Bean实例之前先尝试用后置处理器返回对象的】
1)、resolveBeforeInstantiation(beanName, mbdToUse);解析BeforeInstantiation
希望后置处理器在此能返回一个代理对象;如果能返回代理对象就使用,如果不能就继续
1)、后置处理器先尝试返回对象;
bean = applyBeanPostProcessorsBeforeInstantiation():
拿到所有后置处理器,如果是InstantiationAwareBeanPostProcessor;
就执行postProcessBeforeInstantiation
if (bean != null) {
bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
}
2)、doCreateBean(beanName, mbdToUse, args);真正的去创建一个bean实例;和3.6流程一样;
3)、

  • AnnotationAwareAspectJAutoProxyCreator【InstantiationAwareBeanPostProcessor】 的作用:
    1)、每一个bean创建之前,调用postProcessBeforeInstantiation();
  • 关心MathCalculator和LogAspect的创建
    1)、判断当前bean是否在advisedBeans中(保存了所有需要增强bean)
    2)、判断当前bean是否是基础类型的Advice、Pointcut、Advisor、AopInfrastructureBean,
    或者是否是切面(@Aspect)
    3)、是否需要跳过
    1)、获取候选的增强器(切面里面的通知方法)【List candidateAdvisors】
    每一个封装的通知方法的增强器是 InstantiationModelAwarePointcutAdvisor;
    判断每一个增强器是否是 AspectJPointcutAdvisor 类型的;返回true
    2)、永远返回false

2)、创建对象
postProcessAfterInitialization;
return wrapIfNecessary(bean, beanName, cacheKey);//包装如果需要的情况下
1)、获取当前bean的所有增强器(通知方法) Object[] specificInterceptors
1、找到候选的所有的增强器(找哪些通知方法是需要切入当前bean方法的)
2、获取到能在bean使用的增强器。
3、给增强器排序
2)、保存当前bean在advisedBeans中;
3)、如果当前bean需要增强,创建当前bean的代理对象;
1)、获取所有增强器(通知方法)
2)、保存到proxyFactory
3)、创建代理对象:Spring自动决定
JdkDynamicAopProxy(config);jdk动态代理;
ObjenesisCglibAopProxy(config);cglib的动态代理;
4)、给容器中返回当前组件使用cglib增强了的代理对象;
5)、以后容器中获取到的就是这个组件的代理对象,执行目标方法的时候,代理对象就会执行通知方法的流程;

3)、目标方法执行 ;
容器中保存了组件的代理对象(cglib增强后的对象),这个对象里面保存了详细信息(比如增强器,目标对象,xxx);
1)、CglibAopProxy.intercept();拦截目标方法的执行
2)、根据ProxyFactory对象获取将要执行的目标方法拦截器链;
List chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
1)、List interceptorList保存所有拦截器 5
一个默认的ExposeInvocationInterceptor 和 4个增强器;
2)、遍历所有的增强器,将其转为Interceptor;
registry.getInterceptors(advisor);
3)、将增强器转为List;
如果是MethodInterceptor,直接加入到集合中
如果不是,使用AdvisorAdapter将增强器转为MethodInterceptor;
转换完成返回MethodInterceptor数组;

3)、如果没有拦截器链,直接执行目标方法;
拦截器链(每一个通知方法又被包装为方法拦截器,利用MethodInterceptor机制)
4)、如果有拦截器链,把需要执行的目标对象,目标方法,
	拦截器链等信息传入创建一个 CglibMethodInvocation 对象,
	并调用 Object retVal =  mi.proceed();
5)、拦截器链的触发过程;
	1)、如果没有拦截器执行执行目标方法,或者拦截器的索引和拦截器数组-1大小一样(指定到了最后一个拦截器)执行目标方法;
	2)、链式获取每一个拦截器,拦截器执行invoke方法,每一个拦截器等待下一个拦截器执行完成返回以后再来执行;
		拦截器链的机制,保证通知方法与目标方法的执行顺序;

总结:
1)、  @EnableAspectJAutoProxy 开启AOP功能
2)、 @EnableAspectJAutoProxy 会给容器中注册一个组件 AnnotationAwareAspectJAutoProxyCreator
3)、AnnotationAwareAspectJAutoProxyCreator是一个后置处理器;

4)、容器的创建流程:
1)、registerBeanPostProcessors()注册后置处理器;创建AnnotationAwareAspectJAutoProxyCreator对象
2)、finishBeanFactoryInitialization()初始化剩下的单实例bean
1)、创建业务逻辑组件和切面组件
2)、AnnotationAwareAspectJAutoProxyCreator拦截组件的创建过程
3)、组件创建完之后,判断组件是否需要增强
是:切面的通知方法,包装成增强器(Advisor);给业务逻辑组件创建一个代理对象(cglib);
5)、执行目标方法:
1)、代理对象执行目标方法
2)、CglibAopProxy.intercept();
1)、得到目标方法的拦截器链(增强器包装成拦截器MethodInterceptor)
2)、利用拦截器的链式机制,依次进入每一个拦截器进行执行;
3)、效果:
正常执行:前置通知-》目标方法-》后置通知-》返回通知
出现异常:前置通知-》目标方法-》后置通知-》异常通知

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值