Spring Boot启动时自动运行自定义方法

在springBoot中我们有时候需要让项目在启动时提前加载相应的数据或者执行某个定时任务,那么实现启动时自动运行自定义方法的方式有哪些呢?

1. 实现 CommandLineRunner 接口

@Component
public class TestStart implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        System.out.println("实现 CommandLineRunner 接口");
    }
}

在这里插入图片描述
用于指示Bean包含在SpringApplication中时应运行的接口。
可以在同一应用程序上下文中定义多个CommandLineRunner Bean,并且可以使用有序接口或@order注释对其进行排序

2. 实现 ApplicationRunner 接口

@Component
public class TestStart implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("实现 ApplicationRunner 接口");
    }
}

在这里插入图片描述
用于指示bean包含在SpringApplication中时应运行的接口。
可以定义多个ApplicationRunner Bean

3. 实现 ServletContextAware 接口

@Component
public class TestStart implements ServletContextAware {

    @Override
    public void setServletContext(ServletContext servletContext) {
        System.out.println("实现 ServletContextAware 接口");
    }
}

在这里插入图片描述
该方法会在填充完普通Bean的属性,但是还没有进行Bean的初始化之前执行。

4. 实现 ServletContextListener 接口

@Component
public class TestStart implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("实现 ServletContextListener 接口");
    }

}

在这里插入图片描述
在初始化Web应用程序中的任何过滤器或servlet之前,将通知所有servletContextListener上下文初始化。

5. @Component + @PostConstruct

@Component
public class TestStart {

    @PostConstruct
    public static void test() {
        System.out.println("@Component + @PostConstruct");
    }

}

在这里插入图片描述

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值