springboot项目启动后执行方法,spring boot启动时执行特定方法

  springboot项目启动后执行方法,spring boot启动时执行特定方法

  00-1010 note @ postconstructcommandlinerunner接口实现ApplicationRunner接口,实现ApplicationListener。总结了四种方式的执行顺序。最新的需求是项目启动后立即执行一个方法,然后找到的四个方法都记录在这里。

  00-1010使用注释@PostConstruct是最常见的方式。问题是,如果执行的方法耗时太长,项目将无法在方法执行期间提供服务。

  @ component公共类startinit {///@ autowired可以注入bean//isysuserserviceuserservice;@PostConstruct public void init()抛出interrupted exception { thread . sleep(10 * 1000);//这里,如果方法执行时间过长,项目将永远无法提供服务system . out . println(123456);}}

  00-1010实现CommandLinerunner接口然后调用Run方法中需要调用的方法。这样做的好处是,当执行该方法时,项目已经初始化,可以正常提供服务。

  同时该方法还可以接受参数,可以在项目启动时根据: Java-jar demo . jararg 1 arg 2 arg 3传入的参数进行处理。有关详细信息,请参阅:Spring boot CommandLineRunner启动任务传输参数。

  @Componentpublic类CommandLineRunnerImpl实现CommandLineRunner { @ Override public void run(String.args)抛出异常{ system . out . println(arrays . tostring(args));}}

  00-1010实现ApplicationRunner接口与实现CommandLineRunner接口基本相同。

  唯一的区别是启动时传递的参数的格式。CommandLineRunner对参数格式没有限制,ApplicationRunner接口的参数格式必须是:-key=value

  @Componentpublic类ApplicationRunnerImpl实现application runner { @ Override public void run(application arguments args)抛出异常{ SetString option names=args . get option names();for(String option name : option names){ ListString values=args . getoptionvalues(option name);system . out . println(values . tostring());} }}

  00-1010实现接口ApplicationListener的方式以及ApplicationRunner和CommandLineRunner的接口不影响服务,都可以正常提供服务。注意被监控的事件,通常是ApplicationStartedEvent或ApplicationReadyEvent,其他事件可能不会注入到bean中。

  @Componentpublic类ApplicationListenerImpl实现ApplicationListenerApplicationStartedEvent { @ Override public void on application event(application tionStartedEvent事件){ system . out . println( listener );}}

  00-1010始终首先执行注释方法@PostConstruct。

  如果您正在侦听ApplicationStartedEvent事件,它将在CommandLineRunner和ApplicationRunner之前执行。

  如果监视ApplicationReadyEvent事件,它将在CommandLineRunner和ApplicationRunner之后执行。

  默认情况下,ApplicationRunner首先执行CommandLineRunner和ApplicationRunner。如果双方指定了@Order,则按照@Order的顺序执行,最大的先执行。

  00-1010就这样。本文介绍了Springboot启动后立即执行某个方法的四种方法。关于Springboot启动后执行方法的更多信息,请搜索之前在popular IT上的文章或者继续浏览下面的相关文章。我希望你以后能更多地支持流行音乐!

郑重声明:本文由网友发布,不代表盛行IT的观点,版权归原作者所有,仅为传播更多信息之目的,如有侵权请联系,我们将第一时间修改或删除,多谢。

留言与评论(共有 条评论)
   
验证码: