ApplicationRunner使用

本文来说下CommandLineRunner和ApplicationRunner的使用


ApplicationRunner

使用起来很简单,只需要实现CommandLineRunner或者ApplicationRunner接口,重写run方法就行。在springboot完全初始化完毕后,会执行CommandLineRunner和ApplicationRunner,两者唯一的区别是参数不同,但是不会影响,都可以获取到执行参数


使用示例

代码实例

package com.wideth.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

/***
 * 在springboot完全初始化完毕后,
 * 会执行CommandLineRunner和ApplicationRunner,
 * 两者唯一的区别是参数不同,但是不会影响,都可以获取到执行参数。
 */
@Slf4j
@Component
public class MyApplicationRunner implements ApplicationRunner {


    @Override
    public void run(ApplicationArguments args){

        log.info("====>>> MyApplicationRunner.run()正在执行=========");
    }
}


程序结果

程序结果

在这里插入图片描述


CommandLineRunner

使用示例

代码实例

package com.wideth.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/***
 * 在springboot完全初始化完毕后,
 * 会执行CommandLineRunner和ApplicationRunner,
 * 两者唯一的区别是参数不同,但是不会影响,都可以获取到执行参数。
 */
@Slf4j
@Component
public class MyCommandLineRunner implements CommandLineRunner {


    @Override
    public void run(String... args){

        log.info("====>>> MyCommandLineRunner.run()正在执行=========");
    }
}

程序结果

程序结果

在这里插入图片描述


ApplicationListener

通过事件监听我们也可以实现springboot启动执行方法。实现ApplicationListener,重写onApplicationEvent方法,便可在所有的bean加载完毕后执行。


触发时机

在IOC的容器的启动过程,当所有的bean都已经处理完成之后,spring ioc容器会有一个发布ContextRefreshedEvent事件的动作。


使用实例

使用实例

package com.wideth.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

/***
 * 在IOC的容器的启动过程,
 * 当所有的bean都已经处理完成之后,
 * spring ioc容器会有一个发布
 * ContextRefreshedEvent事件的动作。
 */
@Slf4j
@Component
public class MyApplicationListener implements ApplicationListener<ContextRefreshedEvent> {


    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {

        log.info("====>>> MyApplicationListener.onApplicationEvent()正在执行=========");
    }
}

程序结果

程序结果

在这里插入图片描述


注意问题

系统会存在两个容器,一个是root application context ,另一个就是我们自己的 projectName-servlet context(作为root application context的子容器)

这种情况下,就会造成onApplicationEvent方法被执行两次。为了避免上面提到的问题,我们可以只在root application context初始化完成后调用逻辑代码,其他的容器的初始化完成,则不做任何处理

  //root application context 没有parent
 if (event.getApplicationContext().getParent() == null) { 
 
    //逻辑代码
  }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值