SpringBoot projects executed automatically when you start the specified method

In SpringBoot, there are two ways to achieve the interface starts execution, and are ApplicationRunner CommandLineRunner, different parameters acceptable addition, other similar

ApplicationRunner :

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 继承Application接口后项目启动时会按照执行顺序执行run方法
 * 通过设置Order的value来指定执行的顺序
 */
@Component
@Order(value = 1)
public class StartService implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println(new Date());
    }


}

CommandLineRunner:

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

import java.util.Date;

@Component
public class MyCommandLineRunner implements CommandLineRunner,Ordered{


    @Override
    public int getOrder(){
        return 1;//返回执行顺序
    }

    @Override
    public void run(String... var1) throws Exception{
        System.out.println(new Date());
    }
}

We can also be provided to set the order of execution of the Order, in the above two code also, are annotations @Order (value = 1) and implement the interface implements Ordered manner, like personal annotations, simple.

In the run way we achieve, you can write what we call the method of execution or is already written, the content of personal recommendations to be executed pumped into additional method to write out, after all, when the method started to be executed may be more than one.

Guess you like

Origin blog.csdn.net/rui15111/article/details/80996342