1.CommandLineRunner :
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class MyCommandLineRunner implements CommandLineRunner{
@Override
public void run(String... var1) throws Exception{
System.out.println("Runner!");
}
}
2.ApplicationRunner :
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
@Component
public class MyApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments var1) throws Exception{
System.out.println("Runner!");
}
}
如果想要指定启动方法执行的顺序,可以通过实现org.springframework.core.Ordered接口或者使用org.springframework.core.annotation.Order注解来实现。
1.Ordered接口:
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
@Component
public class MyApplicationRunner implements ApplicationRunner,Ordered{
@Override
public int getOrder(){
return 1;//通过设置这里的数字来知道指定顺序
}
@Override
public void run(ApplicationArguments var1) throws Exception{
System.out.println("Runner!");
}
}
2.Order注解实现方式:
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Order(value = 1)
public class MyApplicationRunner implements ApplicationRunner{
@Override
public void run(ApplicationArguments var1) throws Exception{
System.out.println("Runner!");
}
}
网友评论