02-SpringMVC_常用hock

1.Spring Bean的生命周期

2.BeanFactoryPostProcessor

3.BeanPostProcessor

4.Spring中的各种Aware

5.HttpServletRequestWrapper包装request对象

6.RequestBodyAdvice拦截Request

7.ResponseBodyAdvice拦截Response

8.WebMvcConfigurer配置拦截器和跨域请求等

9.@ControllerAdvice和@ExceptionHandler 实现全局异常处理

10.监听器Listener

11.过滤器Filter

12.拦截器HandlerInterceptor

13.Spring bean 的加载规则

一.Spring Bean的生命周期

B站鲁班学院-学习视频:https://www.bilibili.com/video/BV1fJ411J7x4?p=1arrow-up-right

二.BeanFactoryPostProcessor Bean工厂后置处理器

  • bean工厂的bean属性处理容器,说通俗一些就是可以管理我们的bean工厂内所有的beandefinition(未实例化)数据,可以随心所欲的修改属性

三.BeanPostProcessor

1.Spring提供初始化回调方法(Initializing Callback)有下面三种

且当三个同时存在时,执行顺序为

@PostConstruct----->afterPropertiesSet----->xml中配置的init-method方法

2.Spring Bean 提供的销毁方法有:

1.@PreDestroy方法 2.实现DisposableBean接口后,重写的destroy方法 3.xml中配置的destroy-method方法

且当三个同时存在容器销毁时,执行顺序为

@PreDestroy----->destroy----->xml中配置的destroy-method方法

四.Spring中的各种Aware

参考博客:https://cloud.tencent.com/developer/article/1562066arrow-up-right

1.简介

2.常用的Aware

  • BeanNameAware:能够获取bean的名称,即是id

  • BeanFactoryAware:获取BeanFactory实例

  • ApplicationContextAware:获取ApplicationContext

  • MessageSourceAware:获取MessageSource

  • ResourceLoaderAware:获取ResourceLoader

  • EnvironmentAware:获取Environment

五.继承HttpServletRequestWrapper包装request对象

1.自定义类AuthHttpServletRequestWrapper继承HttpServletRequestWrapper类

2.过滤器中使用

六.实现RequestBodyAdvice接口拦截Request

1 使用:自定义DecryptRequestBodyAdvice继承RequestBodyAdvice

例:

七.实现ResponseBodyAdvice接口-拦截Response

八.WebMvcConfigurer接口-配置拦截器和跨域请求等

参考博客:https://blog.csdn.net/zhangpower1993/article/details/89016503#2.%20WebMvcConfigurer%E6%8E%A5%E5%8F%A3arrow-up-right

常用方法介绍

WebMvcConfigurer接口

  • addInterceptors:拦截器

  • addViewControllers:页面跳转

  • addResourceHandlers:静态资源

  • configureDefaultServletHandling:默认静态资源处理器

  • configureViewResolvers:视图解析器

  • configureContentNegotiation:配置内容裁决的一些参数

  • addCorsMappings:跨域

  • configureMessageConverters:信息转换器

九.@ControllerAdvice和@ExceptionHandler 实现全局异常处理

使用:

  • 1.自定义类上添加@ControllerAdvice注解

  • 2.添加异常处理方法,并在方法上添加@ExceptionHandler注解,注解value值表示捕获处理的异常类型

  • 3.异常处理方法可以定义多个,并根据ExceptionHandler注解value值捕获对应异常

  • 4.异常方法上要添加ResponseBody,并自行处理返回内容

例:

十.监听器Listener

常见的监听器

1.ServletContextListener

2.HttpSessionListener

3.ServletRequestListener

4.ServletContextAttributeListener

5.HttpSessionAttributeListener

6.ServletRequestAttributeListener

7.特别注意:自定义监听器(本质是观察者模式)

参考博客:https://blog.csdn.net/qq_35262405/article/details/103411743arrow-up-right

十一.过滤器 Filter 接口(javax.servlet.Filter)

1.Filter在Spring中的使用: 添加@WebFilter注解并指定拦截规则

十二.拦截器-实现HandlerInterceptor接口

接口方法

  • 1.preHandler方法在Controller业务方法执行之前执行,

  • 2.postHandler方法在Controller业务方法之后执行,

  • 3.afterCompletion方法在最终视图渲染之后返回之前执行,

使用案例:

十三.Spring bean 的加载规则

  • 1.Spring IOC 容器启动时会默认加载单例(Scope=singleton)、非延迟(没有添加@Lazy注解或属性)的spring bean

  • 2.Spriing IOC 容器销毁时只会销毁单例对象(Scope=singleton), 无论该对象是否是延迟加载的

Last updated