ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Springboot启动后执行方法(4种)

2022-08-01 22:37:04  阅读:166  来源: 互联网

标签:CommandLineRunner Springboot 启动 args 接口 ApplicationRunner 执行 public


Springboot启动后执行方法(4种)

一、注解@PostConstruct

使用注解@PostConstruct是最常见的一种方式,存在的问题是如果执行的方法耗时过长,会导致项目在方法执行期间无法提供服务。

@Component
public class StartInit {
//
//    @Autowired   可以注入bean
//    ISysUserService userService;

    @PostConstruct
    public void init() throws InterruptedException {
        Thread.sleep(10*1000);//这里如果方法执行过长会导致项目一直无法提供服务
        System.out.println(123456);
    }
}

二、CommandLineRunner接口

实现CommandLineRunner接口 然后在run方法里面调用需要调用的方法即可,好处是方法执行时,项目已经初始化完毕,是可以正常提供服务的。

同时该方法也可以接受参数,可以根据项目启动时: java -jar demo.jar arg1 arg2 arg3 传入的参数进行一些处理。

@Component
public class CommandLineRunnerImpl implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println(Arrays.toString(args));
    }
}

三、实现ApplicationRunner接口

实现ApplicationRunner接口和实现CommandLineRunner接口基本是一样的。

唯一的不同是启动时传参的格式,CommandLineRunner对于参数格式没有任何限制,ApplicationRunner接口参数格式必须是:–key=value

@Component
public class ApplicationRunnerImpl implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        Set<String> optionNames = args.getOptionNames();
        for (String optionName : optionNames) {
            List<String> values = args.getOptionValues(optionName);
            System.out.println(values.toString());
        }
    }
}

四、实现ApplicationListener

实现接口ApplicationListener方式和实现ApplicationRunner,CommandLineRunner接口都不影响服务,都可以正常提供服务,注意监听的事件,通常是ApplicationStartedEvent 或者ApplicationReadyEvent,其他的事件可能无法注入bean。

@Component
public class ApplicationListenerImpl implements ApplicationListener<ApplicationStartedEvent> {
    @Override
    public void onApplicationEvent(ApplicationStartedEvent event) {
        System.out.println("listener");
    }
}

五、四种方式的执行顺序

注解方式@PostConstruct 始终最先执行

如果监听的是ApplicationStartedEvent 事件,则一定会在CommandLineRunner和ApplicationRunner 之前执行。

如果监听的是ApplicationReadyEvent 事件,则一定会在CommandLineRunner和ApplicationRunner 之后执行。

CommandLineRunner和ApplicationRunner 默认是ApplicationRunner先执行,如果双方指定了@Order 则按照@Order的大小顺序执行,大的先执行。

 

标签:CommandLineRunner,Springboot,启动,args,接口,ApplicationRunner,执行,public
来源: https://www.cnblogs.com/lizm166/p/16542073.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有