SpringBoot项目启动后执行自定义程序

Hello朋友们,我是RatelBlog的李某人。

很多时候我们在开发中会遇到这种场景,就是在项目启动后立刻执行某些自定义的代码。

比如:在项目启动后初始化加载数据、或者进行一些其它的业务操作。

SpringBoot提供了两个接口来帮助我们实现这种需求。这两个接口分别为CommandLineRunner
和ApplicationRunner。它们的执行时机是容器启动完成后。


@FunctionalInterface
public interface ApplicationRunner {

	/**
	 * Callback used to run the bean.
	 * @param args incoming application arguments
	 * @throws Exception on error
	 */
	void run(ApplicationArguments args) throws Exception;

}


@FunctionalInterface
public interface CommandLineRunner {

	/**
	 * Callback used to run the bean.
	 * @param args incoming main method arguments
	 * @throws Exception on error
	 */
	void run(String... args) throws Exception;

}

二者的功能和官方文档一模一样,都是在容器初始化完毕之后执行起run方法

这两个接口的不同之处在于:ApplicationRunner中run方法的参数为ApplicationArguments,
而CommandLineRunner接口中run方法的参数为String数组。
@Component
public class ApplicationRunnerImpl implements ApplicationRunner {

    public static final Logger logger = LoggerFactory.getLogger(ApplicationRunnerImpl.class.getName());

    @Override
    public void run(ApplicationArguments args) throws Exception {
        logger.info("ApplicationRunner OK 项目启动后执行自定义程序如下。。。");
    }
}
@Component
public class CommandLineRunnerImpl implements CommandLineRunner {

    public static final Logger logger = LoggerFactory.getLogger(CommandLineRunnerImpl.class.getName());

    @Override
    public void run(String... args) throws Exception {
         logger.info("CommandLineRunner OK 项目启动后执行自定义程序如下。。。");
    }
}
...
Generating unique operation named: findRbUserListUsingGET_1
Started RatelblogApplication in 4.373 seconds (JVM running for 5.343)
ApplicationRunner OK 项目启动后执行自定义程序如下。。。
CommandLineRunner OK 项目启动后执行自定义程序如下。。。


如果我们有多个实现类,需要按照一定的顺序执行,那么可以通过@Order注解实现。
在实现类上加上@Order注解。@Order(value=整数值)。SpringBoot会按照@Order
中的value值从小到大依次执行。

@Order(value = 2)
@Component
public class ApplicationRunnerImpl implements ApplicationRunner{
 ...
 ...
}

@Order(value = 1)
@Component
public class CommandLineRunnerImpl implements CommandLineRunner {
 ...
 ...
}

...
Generating unique operation named: findRbUserListUsingGET_1
Started RatelblogApplication in 4.373 seconds (JVM running for 5.343)
CommandLineRunner OK 项目启动后执行自定义程序如下。。。
ApplicationRunner OK 项目启动后执行自定义程序如下。。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值