spring web 生命周期理解

spring web /bean 生命周期

反射注解

aop代理类生成 

init servlet  初始化

    load spring-context.xml

    load XmlParser 类解析对象   bean or aop or component-scan or the readding properties 

         // bean

         create bean

         配置bean 属性

         判断 BeanNameAware接口->setBeanName

         判断 BeanFactoryAware接口-> setBeanFactory

         判断 InitializingBean接口 -> afterPropertiesSet

         判断 init-method 属性,调用 bean init

         判断 BeanPostProcessors接口->processAfterInitialization

service servlet   http请求

destroy servlet  销毁

         //bean 

         判断 DisposableBean接口->destroy

         判断 destroy-method属性 调用

以上bean的生命周期可以概括为:

   Bean创建

   Bean属性注入

   Bean 初始化

   Bean销毁

spring boot

    spring boot main : org.springframework.boot.loader.JarLauncher

    扫描注解

     aop代理类生成

    读取appilcation.properties or yml文件

    加载servlet

       初始化Autowired 初始化bean RequestMapping 。。。

    

    其它同上

spring的事件加载抅子

事件类型,按照类型区分:

public class ApplicationEventListener implements ApplicationListener {

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        // 在这里可以监听到Spring Boot的生命周期
        if (event instanceof ApplicationEnvironmentPreparedEvent) { // 初始化环境变量 }
        else if (event instanceof ApplicationPreparedEvent) { // 初始化完成 }
        else if (event instanceof ContextRefreshedEvent) { // 应用刷新 }
        else if (event instanceof ApplicationReadyEvent) {// 应用已启动完成 }
        else if (event instanceof ContextStartedEvent) { // 应用启动,需要在代码动态添加监听器才可捕获 }
        else if (event instanceof ContextStoppedEvent) { // 应用停止 }
        else if (event instanceof ContextClosedEvent) { // 应用关闭 }
        else {}
    }

}

可以针对单事件类型注册:

        SpringApplication application = new SpringApplication(IpsApplication.class);
        application.addListeners(new appEvent());
        application.run(args);
package xx;

import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

public class appEvent implements ApplicationListener<ApplicationReadyEvent> {
    @Override
    public void onApplicationEvent(ApplicationReadyEvent evt) {
        System.out.println("xxxxx app started");
    }
}

每次请求可以增加拦截器

@ControllerAdvice
public class ErrorAdvice {

    @InitBinder
    public void init(){
        
    }

    /**
     * 错误处理
     */
    @ResponseBody
    @ExceptionHandler(value=Exception.class)
    public String errorHandler(Exception ex){
        return "xx";
    }
}

页面的请求可以实现:

1、aop切面实现监控

2、拦截器

3、过滤器

原文地址:https://www.cnblogs.com/a-xu/p/9726289.html