当前位置: 首页 > 后端技术 > Java

有几种方法可以在SpringBoot启动时自动执行代码,还有谁不会呢??

时间:2023-04-01 13:33:12 Java

来源:blog.csdn.net/u011291072/article/details/81813662前言目前开发的SpringBoot项目在启动时需要预加载一些资源。有多种方式可以选择在启动过程中或启动成功后如何执行代码。我们可以在静态代码块中实现,也可以在构造方法中实现,也可以使用@PostConstruct注解。当然你也可以实现Spring的ApplicationRunner和CommandLineRunner接口来实现开机即跑的功能。在这里梳理一下,这些位置的执行和加载顺序的区别。Java自带的启动加载方法staticcodeblockstatic静态代码块是在类加载的时候自动执行的。构造函数方法在对象初始化时执行。执行顺序在static静态代码块之后。Spring启动加载方法@PostConstruct注解PostConstruct注解用在方法上,对象依赖注入初始化后执行。ApplicationRunner和CommandLineRunnerSpringBoot提供了两个接口来实现Spring容器启动后执行的功能。这两个接口是CommandLineRunner和ApplicationRunner。这两个接口都需要实现一个run方法,只需要实现run中的代码即可。这两个接口的功能基本相同,区别在于run方法的入参。ApplicationRunner的run方法的入参是ApplicationArguments,CommandLineRunner的run方法的入参是String数组。ApplicationArguments的官方文档解释为:提供对用于运行SpringApplication的参数的访问。Spring应用运行时使用的访问应用参数。即我们可以获取到SpringApplication.run(...)的应用参数。Order注解当有多个实现CommandLineRunner和ApplicationRunner接口的类时,可以通过在类中添加@Order注解来设置运行顺序。代码测试为了测试启动时运行的效果和顺序,写几段测试代码运行看看。我不会介绍SpringBoot的基础知识。我推荐这个实用教程:https://github.com/javastacks...TestPostConstruct@ComponentpublicclassTestPostConstruct{static{System.out.println("static");}publicTestPostConstruct(){System.out.println("constructer");}@PostConstructpublicvoidinit(){System.out.println("PostConstruct");}}TestApplicationRunner@Component@Order(1)publicclassTestApplicationRunnerimplementsApplicationRunner{@Overridepublicvoidrun(ApplicationArgumentsapplicationArguments)throwsException{System.out.println("order1:TestApplicationRunner");}}TestCommandLineRunner@Component@Order(2)公共类TestCommandLineRunner实现CommandLineRunner{@Overridepublicvoidrun(String...strings)throwsException{System.out.println("order2:TestCommandLineRunner");}}执行结果总结Spring应用在启动过程中,必须自动扫描@Component注解的类,加载类并初始化自动注入对象。加载类时,必须先执行static静态代码块中的代码,然后在对象初始化时执行构造函数。对象注入完成后,调用@PostConstruct注解的方法。当容器启动成功后,按照@Order注解的先后顺序调用CommandLineRunner和ApplicationRunner接口类中的run方法。所以加载顺序是static>constructer>@PostConstruct>CommandLineRunner和ApplicationRunner。近期热点文章推荐:1.1000+Java面试题及答案(2022最新版)2.赞!Java协程来了。..3.SpringBoot2.x教程,太全面了!4.不要用爆破爆满画面,试试装饰者模式,这才是优雅的方式!!5.《Java开发手册(嵩山版)》最新发布,赶快下载吧!感觉不错,别忘了点赞+转发!