Springboot项目启动后执行:CommandLineRunner
原创 crazywind 发表于:2020-01-15 10:43:04
  阅读 :254   收藏   编辑

在实际开发中,我们可能会遇到要在项目启动后执行一些初始化工作,spring为我们提供了CommandLineRunner,我们将初始化

方法逻辑写在run方法中即可

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class StartInit implements CommandLineRunner{

    /**
     * springboot启动后执行
     * @param strings
     * @throws Exception
     */
    @Override
    public void run(String... strings) throws Exception {

        System.out.println("StartInit ...");

    }
}

如果有多个需要初始化的类,我们可以通过注解@Order来设置顺序,优先级按从小到大执行

@Component
@Order(1)
public class StartInit1 implements CommandLineRunner{

}

@Component
@Order(2)
public class StartInit2 implements CommandLineRunner{

}