zoukankan      html  css  js  c++  java
  • SpringBoot 在项目启之后执行自定义方法的两种方式

    前言

    在测试配置中心的配置时,想在项目启动成功之后打印配置项,然后需要执行自定义的类
    一般项目中也会在这个地方进行初始化数据的一些操作

    方式一 实现 CommandLineRunner 接口

    自定义类并实现 CommandLineRunner 接口,实现run()方法,需要执行的语句就放在 run() 方法中
    例:

    @Component
    @Order(1)  // 控制类执行的顺序越小越靠前
    public class StartInitializer implements CommandLineRunner {
        @Override
        public void run(String... args) throws Exception {
            System.out.println("项目启动,执行 CommandLineRunner 实现类的方法");
        }
    }
    

    方式二 实现 ApplicationRunner 接口

    自定义类并实现 ApplicationRunner 接口,实现run()方法,需要执行的语句就放在 run() 方法中
    例:

    @Component
    @Order(2) // 控制类执行的顺序越小越靠前
    public class AppInitializer implements ApplicationRunner {
        @Override
        public void run(ApplicationArguments args) throws Exception {
            System.out.println("项目启动,执行 ApplicationRunner 实现类的方法");
        }
    }
    

    二者区别

    区别在于实现方法 run() 中的参数类型不一样
    实现 ApplicationRunner 接口的 run() 方法参数类型为: ApplicationArguments
    实现 CommandLineRunner 接口的 run() 方法参数类型为: String...

    实现效果


    原文地址: https://www.cnblogs.com/inick/p/15250913.html

  • 相关阅读:
    uu 模块
    程序员都是好男人
    TCP基础知识
    最全 git 命令总结
    iOS 添加UIWindow不显示问题解决
    解决CFBundleIdentifier", Does Not Exist
    Mac 系统OS X>=10.9,怎么把默认的python切换成3.7或者更高
    OC算法练习-Hash算法
    设计模式架构模式
    runtime相关知识
  • 原文地址:https://www.cnblogs.com/inick/p/15250913.html
Copyright © 2011-2022 走看看