java代码启动boot项目_springboot项目启动自动执行代码几种方案

在spring或者springboot项目中,经常会有这样的需求,就是项目启动之后,会执行一段代码,做一些初始化的操作,执行完毕,就不再重复执行。

import javax.servlet.ServletContextListener;

@Component

public class DemoServiceWithServletContextListener implements ServletContextListener{

@Override

public void contextInitialized(ServletContextEvent sce) {

System.out.println("1: run with ServletContextListener , method -> contextInitialized().");

}

import org.springframework.beans.factory.InitializingBean;

@Component

public class DemoServiceWithInitializingBean implements InitializingBean{

@Override

public void afterPropertiesSet() throws Exception {

System.out.println("2: run with InitializingBean , method -> afterPropertiesSet().");

}

import javax.annotation.PostConstruct;

@Component

public class DemoServiceWithPostConstruct {

@PostConstruct

public void run() {

System.out.println("3: run with PostConstruct , method -> run().");

}

import org.springframework.web.context.ServletContextAware;

@Component

public class DemoServiceWithServletContextAware implements ServletContextAware{

@Override

public void setServletContext(ServletContext servletContext) {

System.out.println("4: run with ServletContextAware , method -> setServletContext().");

}

import org.springframework.boot.ApplicationRunner;

@Component

public class DemoServiceWithApplicationRunner implements ApplicationRunner{

@Override

public void run(ApplicationArguments args) throws Exception {

System.out.println("5: run with ApplicationRunner , method -> run().");

}

import org.springframework.boot.CommandLineRunner;

@Component

public class DemoServiceWithCommandLineRunner implements CommandLineRunner{

@Override

public void run(String... args) throws Exception {

System.out.println("6: run with CommandLineRunner , method -> run().");

}

@Component

public class SpringStartListener implements ApplicationListener {

@Override

public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {

}

}

802385dc4573b009abb41fbea0861b59.png

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值