java项目启动时执行的方法

文章介绍了在SpringBoot项目启动前后执行方法的几种方式,包括使用@PostConstruct注解、实现CommandLineRunner和ApplicationRunner接口,以及实现ApplicationListener监听ApplicationStartedEvent和ApplicationReadyEvent事件。@PostConstruct在所有中最早执行,ApplicationListener的事件顺序取决于监听的事件类型,而CommandLineRunner和ApplicationRunner默认按@Order的顺序或默认顺序执行。

1. 在项目启动之前执行的方法

如果需要在项目执行之前执行一些方法,就在目标方法上添加该注解

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

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

2. 在项目启动之后执行的方法

2.1 CommandLineRunner接口

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

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

@Component
public class CommandLineRunnerImpl implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
    	//todo: 需要执行的方法
        System.out.println(Arrays.toString(args));
    }
}


2.2 实现ApplicationRunner接口

实现ApplicationRunner接口和实现CommandLineRunner接口基本是一样的。

唯一的不同是启动时传参的格式,CommandLineRunner对于参数格式没有任何限制,ApplicationRunner接口参数格式必须是:–key=value

@Component
public class ApplicationRunnerImpl implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        Set<String> optionNames = args.getOptionNames();
        for (String optionName : optionNames) {
            List<String> values = args.getOptionValues(optionName);
            System.out.println(values.toString());
        }
    }
}

2.3 实现ApplicationListener

实现接口ApplicationListener方式和实现ApplicationRunner,CommandLineRunner接口都不影响服务,都可以正常提供服务,注意监听的事件,通常是ApplicationStartedEvent 或者ApplicationReadyEvent,其他的事件可能无法注入bean。

@Component
public class ApplicationListenerImpl implements ApplicationListener<ApplicationStartedEvent> {
    @Override
    public void onApplicationEvent(ApplicationStartedEvent event) {
        System.out.println("listener");
    }
}

3. 四种方式的执行顺序

注解方式@PostConstruct 始终最先执行

如果监听的是ApplicationStartedEvent 事件,则一定会在CommandLineRunner和ApplicationRunner 之前执行。

如果监听的是ApplicationReadyEvent 事件,则一定会在CommandLineRunner和ApplicationRunner 之后执行。

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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值