SpringBoot 启动时如何自动运行代码

概述

目前开发的SpringBoot项目在启动的时候需要做一些数据缓存、加载一些资源。最常见的可以去实现Spring的ApplicationRunnerCommandLineRunner接口去实现启动后运行的功能。查阅资料可以知道可以自动运行代码的方式很多包括:

java自身的启动时加载方式

static静态代码块,在类加载的时候即自动执行。

在对象初始化时执行。执行顺序在static静态代码块之后。

Spring启动时加载方式

PostConstruct注解使用在方法上,这个方法在对象依赖注入初始化之后执行。

ApplicationRunner和CommandLineRunner

SpringBoot提供了两个接口来实现Spring容器启动完成后执行的功能,两个接口分别为CommandLineRunnerApplicationRunner

这两个接口需要实现一个run方法,将代码在run中实现即可。这两个接口功能基本一致,其区别在于run方法的入参。ApplicationRunner的run方法入参为ApplicationArguments,为CommandLineRunner的run方法入参为String数组。

举个例子,在Springboot项目中添加以下类,添加到自动扫描包下面

@Component
public class TestPostConstruct {

    static {
        System.out.println("static");
    }
    
    public TestPostConstruct() {
        System.out.println("constructer");
    }

    @PostConstruct
    public void init2() {
        System.out.println("PostConstruct2");
    }

    @PostConstruct
    public void init1() {
        System.out.println("PostConstruct1");
    }

    @PostConstruct
    public void init() {
        System.out.println("PostConstruct");
    }
}
@Component
public class TestApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {
        System.out.println("TestApplicationRunner");
    }
}
@Component
public class TestCommandLineRunner implements CommandLineRunner {
    @Override
    public void run(String... strings) throws Exception {
        System.out.println("TestCommandLineRunner");
    }
}

项目启动结果

Spring应用启动过程中,肯定是要自动扫描有@Component注解的类,加载类并初始化对象进行自动注入。加载类时首先要执行static静态代码块中的代码,之后再初始化对象时会执行构造方法。

在对象注入完成后,调用带有@PostConstruct注解的方法。当容器启动成功后,再根据@Order注解的顺序调用CommandLineRunnerApplicationRunner接口类中的run方法。

当有多个@PostConstruct注解的方法时先运行init方法,其余方法顺序运行。

结论

加载顺序为static>constructer>@PostConstruct>CommandLineRunnerApplicationRunner.

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值