SpringBoot技巧-Java项目启动以后,执行定时任务

 一. SpringBoot启动以后自动执行一些特定的任务或者代码块的方法有哪些?

1. CommandLineRunner接口

@Component
public class CommandLineRunnerTest implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    //业务代码
                    System.out.println("CommandLineRunner:开始轮询去执行定时任务的内容...");
                }
            }
        });
    }
}

CommandLineRunner 是一个接口,用于在Spring Boot应用程序启动后执行一些特定的任务或代码块。当应用程序启动完成后,Spring Boot会查找并执行实现 CommandLineRunner接口的Bean。

它的作用:

  1. 数据库初始化(创建表,插入初始数据)
  2. 预先加载缓存(常用、不频繁更改的数据,存入缓存)
  3. 任务初始化(配置定时任务,确保启动程序后立即执行)
  4. 组件初始化(控制初始化顺序,使用@Order注解指定执行顺序

2. ApplicationRunner接口

import org.springframework.boot.ApplicationArguments;  
import org.springframework.boot.ApplicationRunner;  
import org.springframework.stereotype.Component;  
  
@Component
public class ApplicationRunnerTest implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    //业务代码
                    System.out.println("CommandLineRunner:开始轮询去执行定时任务的内容...");
                }
            }
        });
    }
}

ApplicationRunner接口是Spring Boot提供的一个用于在应用程序启动完成后执行特定任务的接口。它允许你在Spring容器完全启动后,执行一些初始化任务,如加载数据到数据库、预热缓存、检查环境配置等。

它的作用:ApplicationRunner接口是Spring Boot提供的一个用于在应用程序启动完成后执行特定任务的接口。它允许你在Spring容器完全启动后,执行一些初始化任务,如加载数据到数据库、预热缓存、检查环境配置等。

使用方法:

要使用ApplicationRunner,你需要:

  • 创建一个类并实现ApplicationRunner接口。
  • 在该类中实现run(ApplicationArguments args)方法,并在这个方法中编写你希望在应用程序启动后执行的代码。
  • 将这个类通过@Component注解标记为Spring管理的Bean,这样Spring Boot在启动时就能自动发现并运行它。
  • 9
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值