Skip to content

SpringBoot3教程 - 17 启动和停止时执行

我们经常有这样的需求,在项目启动或关闭的时候执行一些代码。

那么可以通过实现 ApplicationRunner DisposableBean 接口来实现:

举个栗子:

java
package com.doubibiji.hellospringboot.base;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class DoubiApplicationInit implements ApplicationRunner, DisposableBean, Ordered {


    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("ApplicationRunnerInit 系统启动...");
    }

    @Override
    public int getOrder() {
        return 0;
    }


    @Override
    public void destroy() throws Exception {
        log.warn("ApplicationRunnerInit 系统关闭...");
    }
}

实现 Ordered 接口是当有多个组件的时候,可以指定执行的顺序。