在springboot项目中启动时需要预加载一些资源,这时需要通过自启动的方式来执行指定任务的代码,可以通过static代码块、构造方法、注解@PostConstruct、ApplicationRunner、CommandLineRunner的方式来实现。下面对几种方式进行简单的分析。
static代码块:static静态代码块在类加载的时候即自动执行。
构造方法:在对象初始化时自动执行,执行顺序在static静态代码块之后。
注解@PostConstruct:@PostConstruct注解使用在方法上,在对象依赖注入初始化之后执行。
ApplicationRunner:在spring容器启动完成之后执行,可以通过注解@Order来指定执行顺序。
CommandLineRunner:在spring容器启动完成之后执行,可以通过注解@Order来指定执行顺序。
实例:
方法一
@Component
public class TestComponent {
static {
System.out.println("static");
}
public TestComponent() {
System.out.println("constructer");
}
@PostConstruct
public void init() {
System.out.println("PostConstruct");
}
}
方法二
@Component
@Order(1)
public class TestApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments applicationArguments) throws Exception {
System.out.println("order1:TestApplicationRunner");
}
}
方法三
@Component
@Order(2)
public class TestCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... strings) throws Exception {
System.out.println("order2:TestCommandLineRunner");
}
}
测试结果:
在springboot工程启动过程中,会自动扫描@Component注解的类,加载类并初始化对象进行注入,加载类时首先执行了static代码块中的代码,然后初始化对象时执行了构造方法,注入后执行了@PostConstruct注解的方法,当spring容器启动完成之后根据@Order注解分别顺序执行了run方法。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/106496.html