SpringBoot项目启动执行任务的几种方式

1、直接在启动类下面调用方法

@SpringBootApplication
public class TestApplication {
    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
        System.out.println("在启动类添加初始下方法");
    }
}

2、使用@PostConstruct注解

@Component
public class MyInitStart2 {
    @PostConstruct
    public void run() {
        System.out.println("在MyInitStart2中添加初始下方法");
    }
}

3、实现CommandLineRunner接口

@Component
public class MyInitStart3 implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("在MyInitStart3中添加初始下方法");
    }
}

4、实现ApplicationRunner接口

@Component
public class MyInitStart4 implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("在MyInitStart4中添加初始下方法");
    }
}

5、实现ApplicationListener接口

@Component
public class MyInitStart5 implements ApplicationListener<ApplicationStartedEvent> {
    @Override
    public void onApplicationEvent(ApplicationStartedEvent event) {
        System.out.println("在MyInitStart5中添加初始下方法");
    }
}

6、实现InitializingBean接口

@Component
public class MyInitStart6 implements InitializingBean {
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("在MyInitStart6中添加初始下方法");
    }
}

7、使用过滤器

@Component
public class MyFilter implements Filter {

    /**
     * init() :该方法在tomcat容器启动初始化过滤器时被调用,它在 Filter 的整个生命周期只会被调用一次。
     * doFilter() :容器中的每一次请求都会调用该方法, FilterChain(放行) 用来调用下一个过滤器 Filter。
     * destroy(): 当容器销毁过滤器实例时调用该方法,在方法中销毁或关闭资源,在过滤器 Filter 的整个生命周期也只会被调用一次。
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("Filter 前置");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("Filter 处理中");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        System.out.println("Filter 后置");
    }
}

8、使用定时器方式

@Component
// 启用定时任务
@EnableScheduling
public class ScheduledTasks {

    // 每 5 秒执行一次任务。
    @Scheduled(cron = "0/5 * * * * ?")
    public void performingTasks() {
        System.out.println("在定时任务中添加初始化方法");
        // 停止定时任务 代码实现省略...
    }
}

以上几种方法的打印顺序:

  1. Filter 前置(过滤器

  2. 在MyInitStart6中添加初始下方法(实现InitializingBean接口

  3. 在MyInitStart2中添加初始下方法(使用@PostConstruct注解

  4. 在MyInitStart5中添加初始下方法(实现ApplicationListener接口

  5. 在MyInitStart4中添加初始下方法(实现ApplicationRunner接口

  6. 在MyInitStart3中添加初始下方法(实现CommandLineRunner接口

  7. 在启动类添加初始下方法(启动类

  8. 在定时任务中添加初始化方法(定时任务

posted @ 2023-04-12 10:09  空还是空  阅读(1379)  评论(0编辑  收藏  举报