栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot项目启动后执行业务的常用方式总结

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot项目启动后执行业务的常用方式总结

项目可能需要启动后就执行一些业务

常见启动时执行的方案

1.使用@PostConstruct注解,不建议使用

注意:这个注解是同步的,会阻塞,如果方法执行时间特别长,可能导致项目启动需要很长时间

2.实现CommandLineRunner,重写run方法,在run方法中执行,如果有多个,对执行顺序有要求就加@Order,小的先执行

示例代码:

import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Order(2)
public class MyCommandLineRunner implements CommandLineRunner {

    @Override

    public void run(String... args) throws Exception {
        System.out.println("通过实现CommandLineRunner,实现服务启动执行后需要执行的业务");
    }

}

3.实现ApplicationRunner,重写run方法,在run方法中执行,如果有多个,对执行顺序有要求就加@Order,小的先执行(和2的区别是此处run方法的参数重新封装了,而2处的参数是原始参数)

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Order(3)
public class MyApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("通过实现ApplicationRunner,实现服务启动执行后需要执行的业务");
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/322332.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号