首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >SpringBoot框架 项目启动时执行

SpringBoot框架 项目启动时执行

作者头像
郭顺发
发布2023-07-07 11:28:06
发布2023-07-07 11:28:06
3900
举报
文章被收录于专栏:pandacode_cnpandacode_cn

有时需要在项目启动时加载一部分数据,这时就要有一部分代码在项目启动时运行。

Springboot项目实现启动时运行代码的方式有四种。

1. PostConstruct注解

代码语言:javascript
复制
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class Init1 {

    @PostConstruct
    public void init() {
        System.out.println("init1");
    }

}

2. 实现InitializingBean接口

代码语言:javascript
复制
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

@Component
public class Init2 implements InitializingBean {
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("init2");
    }
}

3. 实现CommandLineRunner接口

可以通过在类型加@Order注解来控制执行顺序。

代码语言:javascript
复制
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class Init3 implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("init3");
    }
}

4. 放在SpringBoot启动类中

代码语言:javascript
复制
@SpringBootApplication
public class PandaBaseApplication {

    public static void main(String[] args) {
        SpringApplication.run(PandaBaseApplication.class, args);
        System.out.println("init4");
    }

}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-07-01 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. PostConstruct注解
  • 2. 实现InitializingBean接口
  • 3. 实现CommandLineRunner接口
  • 4. 放在SpringBoot启动类中
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档