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 注解方式;使用场景多数是预加载数据到缓存中。

猜你喜欢

转载自blog.csdn.net/weixin_45626288/article/details/132701239