SpringBoot项目启动时预加载

SpringBoot项目启动时预加载

在这里插入图片描述

Spring Boot是一种流行的Java开发框架,它提供了许多方便的功能来简化应用程序的开发和部署。其中一个常见的需求是在Spring Boot应用程序启动时预加载一些数据或执行一些初始化操作。

1. CommandLineRunner 和 ApplicationRunner

Spring Boot提供了CommandLineRunnerApplicationRunner接口,它们允许您在应用程序启动时执行特定的代码。您可以创建一个实现这些接口的Bean,并在run方法中编写初始化逻辑。这些接口的主要区别在于传递给run方法的参数类型不同,您可以根据需要选择其中之一。

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class MyCommandLineRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        // 在这里执行初始化操作
    }
}
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
public class MyApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 在这里执行初始化操作
    }
}

2. @PostConstruct 注解

您还可以使用@PostConstruct注解来标记一个方法,在Spring容器初始化Bean时会自动调用该方法。这是一种更简单的方式,适用于不需要访问命令行参数或应用程序参数的初始化操作。

import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;

@Component
public class MyInitializer {
    @PostConstruct
    public void initialize() {
        // 在这里执行初始化操作
    }
}

3. 实现 ApplicationListener

如果您需要监听应用程序上下文的初始化事件,可以实现ApplicationListener接口。这允许您定义一个监听器来捕获ContextRefreshedEvent事件,该事件在应用程序上下文初始化完成后触发。

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

@Component
public class MyContextRefreshedListener implements ApplicationListener<ContextRefreshedEvent> {
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        // 在这里执行初始化操作
    }
}

4. 使用 @EventListener 注解

除了实现ApplicationListener接口,您还可以使用@EventListener注解来创建事件监听器方法。这种方式更加灵活,允许您在普通的Spring Bean方法上添加事件监听器。

import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.springframework.context.event.EventListener;

@Component
public class MyEventListener {

    @EventListener(ContextRefreshedEvent.class)
    public void onContextRefreshedEvent() {
        // 在这里执行初始化操作
    }
}

个人在项目中比较喜欢使用@PostConstruct 注解方式;使用场景多数是预加载数据到缓存中。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LOVE_DDZ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值