SpringBoot 启动 停止 监听

SpringBoot提供了多种监听方式进行应用的启动停止监听,下面列举两种监听方式,便于在应用启动完成进行数据初始化或者在应用停止时进行垃圾回收,数据清理等等。

示例一
SpringBoot启动监听 ApplicationRunner
自定义ApplicationRunner 实现类,使用注解@Component把该实现类交于IOC管理。在SpringBoot启动成功后就会执行实现类的回调。

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
public class ApplicationRunnerListener implements ApplicationRunner {

    private static Logger logger = LoggerFactory.getLogger(ApplicationRunnerListener.class);

    @Override
    public void run(ApplicationArguments args) throws Exception {
        logger.info("程序已运行");
    }
}

示例二
SpringBoot启动监听 ApplicationListener
自定义ApplicationListener 实现类,使用注解@Component把该实现类交于IOC管理。在SpringBoot启动成功后就会执行实现类的回调。

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

@Component
public class ApplicationReadyEventListener implements ApplicationListener<ApplicationReadyEvent> {

    private static final Logger logger = LoggerFactory.getLogger(ApplicationReadyEventListener.class);

    @Override
    public void onApplicationEvent(ApplicationReadyEvent contextReadyEvent) {
        logger.info("程序已启动");
    }
}

示例三
SpringBoot停止监听 ApplicationListener
自定义ApplicationListener 实现类,使用注解@Component把该实现类交于IOC管理。在SpringBoot启动成功后就会执行实现类的回调。

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.stereotype.Component;

@Component
public class ApplicationClosedEventListener implements ApplicationListener<ContextClosedEvent> {
    private static Logger logger = LoggerFactory.getLogger(ApplicationClosedEventListener.class);

    @Override
    public void onApplicationEvent(ContextClosedEvent contextClosedEvent) {
        logger.info("程序已停止");
    }
}
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值