实际应用中,希望项目启动的时候就去做一些事情,比如数据加载。springboot提供了实现这一需求,通过实现接口CommandLineRunner来实现
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
public class Command implements CommandLineRunner{
@Override
public void run(String...args) throws Exception{
System.out.println("启动后执行");
}
}
指定顺序执行,@Order注解
Demo1
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Order(value=1)
public class Command implements CommandLineRunner{
@Override
public void run(String...args) throws Exception{
System.out.println("启动后执行");
}
}
Demo2
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Order(value=2)
public class CommandNext implements CommandLineRunner{
@Override
public void run(String...args) throws Exception{
System.out.println("next执行");
}
}
执行顺序: