springboot中自启动方式浅析

本文详细介绍了在SpringBoot项目启动时如何通过static代码块、构造方法、@PostConstruct注解、ApplicationRunner和CommandLineRunner来预加载资源。分析了各种方式的执行顺序,并提供了示例代码,展示了它们在实际应用中的执行流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在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方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值