springboot 启动时执行任务CommandLineRunner

平常开发中有可能需要实现在项目启动后执行的功能,SpringBoot提供的一种简单的实现方案就是添加一个model并实现CommandLineRunner接口,实现功能的代码放在实现的run方法中

如果有多个类实现CommandLineRunner接口,如何保证顺序
SpringBoot在项目启动后会遍历所有实现CommandLineRunner的实体类并执行run方法,如果需要按照一定的顺序去执行,那么就需要在实体类上使用一个@Order注解(或者实现Order接口)来表明顺序

注意: @Order 注解的执行优先级是按value值从小到大顺序。

代码如下:

第一个类:

package com.ws.util;

import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @ClassName OpenTest
 * @Description TODO
 * @Date 14:52 2019/6/14
 * @Author Ws
 * @Version 1.0
 **/
@Component
@Order(value = 1)
public class OpenTest implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("这是启动第一个数据库");
    }
}

第二个类

package com.ws.util;

import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @ClassName OpenTest
 * @Description TODO
 * @Date 14:52 2019/6/14
 * @Author Ws
 * @Version 1.0
 **/
@Component
@Order(value = 2)
public class OpenTest2 implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("这是启动第二个数据库");
    }
}

控制台打印:
在这里插入图片描述

发布了89 篇原创文章 · 获赞 47 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43726822/article/details/92066669