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

java开发的SpringBoot实现代码自动执行

时间:2023-04-01 18:00:10 Java

前言目前开发的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注解来设置运行顺序。代码测试为了测试启动时运行的效果和顺序,写几段测试代码运行看看。TestPostConstruct@ComponentpublicclassTestPostConstruct{static{System.out.println("static");}publicTestPostConstruct(){System.out.println("constructer");}@PostConstructpublicvoidinit(){System.out.println("PostConstruct");}}TestApplicationRunner@Component@Order(1)公共类TestApplicationRunner实现ApplicationRunner{@Overridepublicvoidrun(ApplicationArgumentsapplicationArguments)throwsException{System.out.println("order1:TestApplicationRunner");}}TestCommandLineRunner@Order(2)publicclassTestCommandLineRunnerimplementsCommandLineRunner{@Overridepublicvoidrun(String...strings)throwsException{System.out.println("order2:TestCommandLineRunner");}}执行结果总结Spring应用启动流程,没错自动扫描@Component注解的类,加载类并初始化对象,实现自动注入。加载类时,首先要执行静态代码块中的代码,java训练后对象初始化时会执行构造函数。对象注入完成后,调用@PostConstruct注解的方法。当容器启动成功后,按照@Order注解的先后顺序调用CommandLineRunner和ApplicationRunner接口类中的run方法。所以加载顺序是static>constructer>@PostConstruct>CommandLineRunner和ApplicationRunner。文章来源:Java知音