Spring Boot 进行初始化资源的几种方式

本文介绍了在Spring Boot中进行资源初始化的三种方式:1) 使用@PostConstruct注解,适用于不依赖其他Spring beans的初始化;2) 实现CommandLineRunner接口,在所有Spring Beans初始化后执行;3) 实现ApplicationRunner接口,提供了ApplicationArguments对象以获取更多项目信息。这些方法在应用启动时按特定顺序执行。
摘要由CSDN通过智能技术生成

一、@PostConstruct 注解完成资源初始化操作

使用@PostConstruct注解完成资源初始化操作,但前提这些初始化操作不需要依赖于其它Spring beans 的初始划工作。

测试样例:

    @PostConstruct
    public void init(){
        System.out.println("@PostConstruct初始化");
    }

  注意:1.只有一个非静态方法能是使用次注解。2.被注解的方法不得有任何参数。3.被注解的方法返回值必须为void。4.被注解方法不得抛出已检查异常。5.此方法只会被执行一次。

二、CommandLineRunner

定义初始化类MyCommandLineRunner,注册成Bean,添加@Component注解。实现CommandLineRunner接口,并实现它的run()方法,在run方法中实现初始化逻辑。

测试样例:

package test.ysj.controller;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
public class MyCommandLineRunner implements CommandLineRunner {
   
    @Override
    public void run(String... args) throws Exception {
        System.out.println("项目初始化---------------1&
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值