# SpringBoot3教程 - 17 启动和停止时执行
我们经常有这样的需求,在项目启动或关闭的时候执行一些代码。
那么可以通过实现 ApplicationRunner 和 DisposableBean 接口来实现:
举个栗子:
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 系统关闭...");
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
实现 Ordered 接口是当有多个组件的时候,可以指定执行的顺序。
