🐻SpringBoot项目启动后执行方法的三种方式

使用场景:可以在程序启动时加载一些自定义的监听器之类的,例如Socket服务的监听器,此时如果使用@PostConstract,Socket服务的监听器将阻塞启动程序,导致程序不能正常启动。

方式一:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
 
/**
 * @author zhangzhixi
 * @version 1.0
 * @description SpringBoot项目加载后执行,演示一:实现 ApplicationListener 接口
 * @date 2023-07-17 10:26
 */
@Component
@Slf4j
public class ProjectLoadExecuteDemo1 implements ApplicationListener<ContextRefreshedEvent> {
 
 
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
      if (event.getApplicationContext().getParent() == null) {
          log.info("SpringBoot项目加载后执行,演示一:实现 ApplicationListener 接口");
      }
    }
}

方式二:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
 
/**
 * @author zhangzhixi
 * @version 1.0
 * @description SpringBoot项目加载后执行,演示二:实现 ApplicationRunner 接口
 * @date 2023-07-17 10:26
 */
@Component
@Slf4j
public class ProjectLoadExecuteDemo2 implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("SpringBoot项目加载后执行,演示二:实现 ApplicationRunner 接口");
    }
}

方式三:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
 
/**
 * @author zhangzhixi
 * @version 1.0
 * @description SpringBoot项目加载后执行,演示三:实现 ApplicationRunner 接口
 * @date 2023-07-17 10:26
 */
@Component
@Slf4j
public class ProjectLoadExecuteDemo3 implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        log.info("SpringBoot项目加载后执行,演示三:实现 CommandLineRunner 接口");
    }
}

posted @   Java小白的搬砖路  阅读(2776)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?

喜欢请打赏

扫描二维码打赏

支付宝打赏

点击右上角即可分享
微信分享提示