SpringBoot在项目启动之后执行自定义方法的两种方式分别是什么,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
SpringBoot项目启动之后执行自定义方法的两种方式
在测试配置中心的配置时,想在项目启动成功之后打印配置项,然后需要执行自定义的类
一般项目中也会在这个地方进行初始化数据的一些操作
方式一实现CommandLineRunner接口
自定义类并实现CommandLineRunner接口,实现运行()方法,需要执行的语句就放在运行()方法中
例:
@ component @Order(1),,//,控制类执行的顺序越小越靠前 public class  StartInitializer implements CommandLineRunner  { ,,@Override ,,,public void 运行(字符串…,args), throws Exception { ,,,,,,,System.out.println(“项目启动,执行,CommandLineRunner 实现类的方法“); ,,,} }
方式二实现ApplicationRunner接口
自定义类并实现ApplicationRunner接口,实现运行()方法,需要执行的语句就放在运行()方法中
例:
@ component @Order(2),//,控制类执行的顺序越小越靠前 public class  AppInitializer implements ApplicationRunner  { ,,@Override ,,,public void 运行(ApplicationArguments args), throws Exception { ,,,,,,,System.out.println(“项目启动,执行,ApplicationRunner 实现类的方法“); ,,,} }
二者区别
区别在于实现方法()中运行的参数类型不一样
实现ApplicationRunner接口的运行()方法参数类型为:ApplicationArguments
实现CommandLineRunner接口的运行()方法参数类型为:字符串…
<>强实现效果强>
SpringBoot项目启动后执行某些自定义代码
SpringBoot给我们提供了两种“开机启动”某些方法的方式:ApplicationRunner和CommandLineRunner。
这两种方法提供的目的是为了满足,在项目启动的时候立刻执行某些方法。我们可以通过实现ApplicationRunner和CommandLineRunner,来实现,他们都是在SpringApplication执行之后开始执行的。
CommandLineRunner接口可以用来接收字符串数组的命令行参数,ApplicationRunner是使用ApplicationArguments用来接收参数的
代码示例
@ component//被春容器管理 @Order(1)//如果多个自定义ApplicationRunner,用来标明执行顺序 public class  MyApplicationRunner implements ApplicationRunner  { ,,@Override ,,,public void 运行(ApplicationArguments applicationArguments), throws Exception { ,,,,,,,System.out.println(“- - - - - - - - - - - - - - - -在“,+,“项目启动,现在=?+,new 日期()); ,,,,,,,定时器(); ,,,} ,,,public static void 定时器(){ ,,,,,,,Timer Timer =, new 计时器(); ,,,,,,,timer.schedule (new TimerTask (), { ,,,,,,,,,,@Override ,,,,,,,,,,,public void 运行(),{ ,,,,,,,,,,,,,,,System.out.println(“- - - - - -定时任务- - - - - - - - - -“); ,,,,,,,,,,,} ,,,,,,,},,0,1000); ,,,} }
执行结果
2018-02-08 14:10:16.490 信息10236 - - - - - - (,,,,,,,,,主要s.b.c.e.t。TomcatEmbeddedServletContainer: Tomcat启动>看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注行业资讯频道,感谢您对的支持。
SpringBoot在项目启动之后执行自定义方法的两种方式分别是什么