Springboot启动后执行方法的四种方式

本文介绍了在Spring Boot应用启动后立即执行指定方法的四种方法:@PostConstruct注解、CommandLineRunner接口、ApplicationRunner接口以及实现ApplicationListener接口。其中,@PostConstruct在所有方法中最早执行,可能导致服务延迟。CommandLineRunner和ApplicationRunner接口允许在项目初始化完毕后执行,且ApplicationRunner具有更严格的参数格式。实现ApplicationListener接口则允许监听特定事件来决定执行时机,如ApplicationStartedEvent或ApplicationReadyEvent。
摘要由CSDN通过智能技术生成

最新需要在项目启动后立即执行某个方法,然后特此记录下找到的四种方式

注解@PostConstruct

使用注解@PostConstruct是最常见的一种方式,存在的问题是如果执行的方法耗时过长,会导致项目在方法执行期间无法提供服务。

@Component
public class StartInit {
//
//    @Autowired   可以注入bean
//    ISysUserService userService;

    @PostConstruct
    public void init() throws InterruptedException {
        Thread.sleep(10*1000);//这里如果方法执行过长会导致项目一直无法提供服务
        System.out.println(123456);
    }
}

CommandLineRunner接口

实现CommandLineRunner接口 然后在run方法里面调用需要调用的方法即可,好处是方法执行时,项目已经初始化完毕,是可以正常提供服务的。

同时该方法也可以接受参数,可以根据项目启动时: java -jar demo.jar arg1 arg2 arg3 传入的参数进行一些处理。详见: Spring boot CommandLineRunner启动任务传参

@Component
public class CommandLineRunnerImpl implements CommandLineRunner {
    @Override
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值