广告
返回顶部
首页 > 资讯 > 后端开发 > Python >SpringBoot 在项目启动之后执行自定义方法的两种方式小结
  • 701
分享到

SpringBoot 在项目启动之后执行自定义方法的两种方式小结

2024-04-02 19:04:59 701人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

目录SpringBoot 项目启动之后执行自定义方法的两种方式方式一 实现 CommandLineRunner 接口方式二 实现 ApplicationRunner 接口二者区别sp

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...

实现效果

Springboot 项目启动后执行某些自定义代码

Springboot给我们提供了两种“开机启动”某些方法的方式:ApplicationRunner和CommandLineRunner。

这两种方法提供的目的是为了满足,在项目启动的时候立刻执行某些方法。我们可以通过实现ApplicationRunner和CommandLineRunner,来实现,他们都是在SpringApplication 执行之后开始执行的。

CommandLineRunner接口可以用来接收字符串数组的命令行参数,ApplicationRunner 是使用ApplicationArguments 用来接收参数的

代码示例


@Component//被spring容器管理
@Order(1)//如果多个自定义ApplicationRunner,用来标明执行顺序
public class MyApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {
        System.out.println("-------------->" + "项目启动,now=" + new Date());
        myTimer();
    }
    public static void myTimer(){
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("------定时任务--------");
            }
        }, 0, 1000);
    }
}

执行结果

2018-02-08 14:10:16.490  INFO 10236 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8081 (Http)
-------------->项目启动,now=Thu Feb 08 14:10:16 CST 2018
------定时任务--------
2018-02-08 14:10:16.497  INFO 10236 --- [           main] com.mlxs.springboot01.WEB.MainApp        : Started MainApp in 5.595 seconds (JVM running for 6.334)
------定时任务--------
------定时任务--------
------定时任务--------
------定时任务--------
------定时任务--------
------定时任务--------

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

--结束END--

本文标题: SpringBoot 在项目启动之后执行自定义方法的两种方式小结

本文链接: https://www.lsjlt.com/news/136173.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作