springboot项目启动后执行业务的常用方式总结
项目可能需要启动后就执行一些业务
常见启动时执行的方案
1.使用@PostConstruct注解,不建议使用
注意:这个注解是同步的,会阻塞,如果方法执行时间特别长,可能导致项目启动需要很长时间
2.实现CommandLineRunner,重写run方法,在run方法中执行,如果有多个,对执行顺序有要求就加@Order,小的先执行
示例代码:
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Order(2)
public class MyCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("通过实现CommandLineRunner,实现服务启动执行后需要执行的业务");
}
}
3.实现ApplicationRunner,重写run方法,在run方法中执行,如果有多个,对执行顺序有要求就加@Order,小的先执行(和2的区别是此处run方法的参数重新封装了,而2处的参数是原始参数)
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Order(3)
public class MyApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("通过实现ApplicationRunner,实现服务启动执行后需要执行的业务");
}
}
还没有评论,来说两句吧...