• 【SpringBoot】 启动后执行方法的五种方式


    在 SpringBoot 工程 启动后, 执行方法的五种方式:

    1、实现 CommandLineRunner 接口

    项目初始化完毕后,才会调用方法,提供服务

    @Component
    public class StartInit2 implements CommandLineRunner {
    
        @Override
        public void run(String... args) throws Exception {
            System.out.println("CommandLineRunner====================");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    2、实现 ApplicationRunner 接口

    同 CommandLineRunner。只是传参格式不一样。CommandLineRunner:没有任何限制;ApplicationRunner:key-value

    @Component
    public class StartInit3 implements ApplicationRunner {
    
        @Override
        public void run(ApplicationArguments args) {
            System.out.println("ApplicationRunner=================");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    3、实现 ApplicationListener 接口

    项目初始化完毕后,才会调用方法,提供服务。注意监听的事件,通常是 ApplicationStartedEvent 或者 ApplicationReadyEvent,其他的事件可能无法注入 bean。

    @Component
    public class StartInit4 implements ApplicationListener<ApplicationStartedEvent> {
    
        @Override
        public void onApplicationEvent(ApplicationStartedEvent event) {
            System.out.println("ApplicationListener================ApplicationStartedEvent");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 如果监听的是 ApplicationStartedEvent 事件,则 ApplicationListener 一定会在 CommandLineRunner 和 ApplicationRunner 之前执行;
    • 如果监听的是 ApplicationReadyEvent 事件,则 ApplicationListener 一定会在 CommandLineRunner 和 ApplicationRunner 之后执行;

    顺序:
    默认是 ApplicationRunner 先执行,如果双方指定了@Order 则按照 @Order的大小顺序执行,小的先执行。

    原理:

    1. SpringApplication 的run方法会执行afterRefresh方法。
    2. afterRefresh方法会执行callRunners方法。
    3. callRunners方法会调用所有实现ApplicationRunner和CommondLineRunner接口的方法callRunners方法会调用所有实现ApplicationRunner和CommondLineRunner接口的方法

    4、@PostConstruct 注解

    在项目初始化过程中,就会调用此方法。如果业务逻辑执行很耗时,可能会导致项目启动失败。

    @Component
    public class StartInit {
    
        @PostConstruct
        public void init() {
            System.out.println("@PostConstruct===============================");
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    5、实现 InitializingBean 接口

    项目启动时,调用此方法

    @Component
    public class StartInit6 implements InitializingBean {
    
        @Override
        public void afterPropertiesSet() {
            System.out.println("InitializingBean====================");
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
  • 相关阅读:
    高阶数据结构学习之跳表
    七月集训(第20天) —— 二叉搜索树
    Docker安装Redis 7.x单机模式
    QGIS开发笔记(三):Windows安装版二次开发环境搭建(下):将QGis融入QtDemo,添加QGis并加载tif遥感图的Demo
    解决dataset.mnist无法加载进去的情况
    测试基础——数据库及数据库表的SQL操作(了解即可)
    C++ Qt 学习(十):Qt 其他技巧
    Python函数
    poi包工具类
    LC15.三数之和、LC22括号生成
  • 原文地址:https://blog.csdn.net/sco5282/article/details/126365408