当前位置: 首页 > 科技观察

SpringBoot启动时自动执行代码的几种方式

时间:2023-03-13 19:03:06 科技观察

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数组。WhatistheofficialdocumentofApplicationArgumentsexplainedas:"ProvidesaccesstotheargumentsthatwereusedtorunaSpringApplication.访问应用程序运行时使用的应用程序参数。即我们可以获取SpringApplication.run(...).Order注解当多个类实现了CommandLineRunner和ApplicationRunner接口时,可以通过在类中添加@Order注解来设置运行顺序。代码测试为了测试启动时运行的效果和顺序,写几段测试代码运行看看。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:RunTestApplicationRunner");}}TestCommandLine@Component@Order(2)publicclassTestCommandLineRunnerimplementsCommandLineRunner{@Overridepublicvoidrun(String...strings)throwsException{System.out.println("order2:TestCommandLineRunner");}}执行结果总结Spring应用启动流程其中肯定要自动扫描@Component注解的类,加载类并初始化对象进行自动注入。加载类时,必须先执行static静态代码块中的代码,然后在对象初始化时执行构造函数。对象注入完成后,调用@PostConstruct注解的方法。当容器启动成功后,按照@Order注解的先后顺序调用CommandLineRunner和ApplicationRunner接口类中的run方法。所以加载顺序是static>constructer>@PostConstruct>CommandLineRunner和ApplicationRunner。