【项目启动执行指定代码】⭐️通过案例测试下常用的实现方式

目录

前言

1、监听 ApplicationContext事件

2、实现CommandLineRunner接口

3、实现ApplicationRunner接口

4、使用@PostConstruct注解

章末


前言

        为了保证程序在启动后的稳定性,需要执行初始化操作,像加载配置,建立数据库连接可以在项目启动时实现,另外一个场景就是缓存预热,就是说要提前将热点数据更新到redis缓存中,防止高并发情况下造成缓存击穿,这个过程需要在初始化的时候,执行查询热点数据、更新redis操作,这里常见的实现方式大概有以下几个方法:

1、监听 ApplicationContext事件

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 contextRefreshedEvent) {
              //todo 指定初始化操作
、            System.out.println("监听到contextRefreshedEvent事件,开始初始化操作--------------------");
    }
}

        创建配置类实现ApplicationListener接口,重写onApplicationEvent()方法,加上@Component注解标识为配置类,这样启动的时候才会扫描到这里

        适用场景:

1.执行一次性初始化操作

        比如加载基础数据,建立连接等可以确保初始化操作在应用程序启动后立即执行

2.初始化缓存等

2、实现CommandLineRunner接口

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

@Component
public class MyCommandLineRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        //todo    指定初始化代码
        System.out.println("MyCommandLineRunner调用了run()方法---------------");
    }
}

        重写CommandLineRunner的run方法,也会在springboot 项目启动后执行,方法参数是字符串数组,可以直接获取命令行参数

        适用场景:

 项目完全启动后执行一些需要访问Spring上下文或者命令行参数的任务

3、实现ApplicationRunner接口

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
public class ApplicationArgumentProcessor implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        //todo  初始化操作
        System.out.println("检测到 ApplicationArgumengProcessor 类中的额run方法并执行-------------------------");
    }
}

        ApplicationRunner接口的run方法会在项目启动后执行,可以获取命令行参数

        适用场景:

 比如数据初始化,特定服务的启动等

4、使用@PostConstruct注解

    @Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {
        //...

        @PostConstruct
	public void init(){
		System.out.println("UserService初始化bean后执行----------");
	}
}	

         @PostConstruct 注解用于标记一个方法,该方法会在spring Bean 实例化后立即执行

        适用场景:

在Spring Bean初始化时执行一些操作,比如资源加载,依赖注入等,通常用于单个Bean的初始化

章末

        文章到这里就结束了~

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

先锋 Coder

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

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

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

打赏作者

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

抵扣说明:

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

余额充值