springboot非web环境一次性执行代码

需求描述:

  希望使用springboot的基础功能,但是不想通过web方式调用,而是在springboot启动以后自动执行一些代码。

 

方法:

  可以实现如下两个接口中的任意一个:ApplicationRunner or CommandLineRunner。它们的run方法都会在springboot启动以后执行。

 

步骤:

  1.编写一个类实现ApplicationRunner 或者 CommandLineRunner接口,在这两个接口的实现方法(run方法)中就可以编写自己希望在springboot启动以后自动执行的代码。

  2.将这个类加上@Component注解。

  3.启动springboot。

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

@Component
public class MyCommandLineRunner implements CommandLineRunner {

    @Override
    public void run(String... args) {
        // Do something...
    }

}

 

说明:

  在run方法中,我们会需要调用在springboot中注册的各个组件,这些组件直接通过@autowired注入进来即可。

 

参考链接:https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.spring-application.command-line-runner

 

  

posted @ 2021-08-09 09:40  tom不是猫  阅读(223)  评论(0编辑  收藏  举报