SpringBoot笔记:启动加载类CommandLineRunner

如果在SpringBoot应用启动的时候需要执行特定的动作,可以利用CommandLineRunner。实现了CommandLineRunner接口的Component会在所有Spring Beans都初始化之后,SpringApplication.run()之前执行,非常适合在应用程序启动之初进行一些数据初始化的工作。

准备3个类来验证下启动时的执行顺序。

第1个类是Controller类,我们定义一般不需要的构造方法,并输出一条日志

第2个类是CommandLineRunner类,通过@Order标记执行顺序为1,在run方法里面输出日志

第3个类是CommandLineRunner类,通过@Order标记执行顺序为2,在run方法里面输出日志

执行SpringApplication.run,查看console中的输出日志,CommandLineRunner的日志会按照Order从小到大执行,并且在Spring Beans初始化之后执行。

猜你喜欢

转载自blog.csdn.net/weixin_42114804/article/details/84995961