弹簧引导启动加载数据原理分析

  

实际应用中,我们会有在项目服务启动的时候就去加载一些数据或做一些事情这样的需求。

  

为了解决这样的问题,弹簧引导为我们提供了一个方法,通过实现接口CommandLineRunner来实现。

  

创建实现接口CommandLineRunner的类,通过@ component注解,就可以实现启动时加载数据项。使用@Order注解来定义执行顺序。

  

IndexStartupRunner.Java类:         进口org.springframework.boot.CommandLineRunner;   进口org.springframework.core.annotation.Order;   进口org.springframework.stereotype.Component;/* *   *服务启动执行   */@ component   @Order (value=https://www.yisu.com/zixun/1)   公共类IndexStartupRunner实现CommandLineRunner {   @Override   公共空间运行(字符串…args)抛出异常{   系统。出.打印("   IndexStartupRunner   在在在在在在在在在在在在在在在服务启动执行,执行加载数据等操作& lt; & lt; & lt; & lt; & lt; & lt; & lt; & lt; & lt; & lt; & lt; & lt; & lt;”);   }   }   IndexStartupRunner2.java类:   进口org.springframework.boot.CommandLineRunner;   进口org.springframework.core.annotation.Order;   进口org.springframework.stereotype.Component;/* *   *服务启动执行   */@ component   @Order (value=https://www.yisu.com/zixun/2)   公共类IndexStartupRunner2实现CommandLineRunner {   @Override   公共空间运行(字符串…args)抛出异常{   系统。出.打印("   IndexStartupRunner2   在在在在在在在在在在在在在在在服务启动执行,执行加载数据等操作& lt; & lt; & lt; & lt; & lt; & lt; & lt; & lt; & lt; & lt; & lt; & lt; & lt;”);   }   }      

启动程序后,控制台输出结果为:
  

  

在在在在在在在在在在在在在在在IndexStartupRunner服务启动执行,执行加载数据等操作& lt; & lt; & lt; & lt; & lt; & lt; & lt; & lt; & lt; & lt; & lt; & lt; & lt;
  在在在在在在在在在在在在在在在IndexStartupRunner2服务启动执行,执行加载数据等操作& lt; & lt; & lt; & lt; & lt; & lt; & lt; & lt; & lt; & lt; & lt; & lt; & lt;

  

根据控制台结果可判断,@Order注解的执行优先级是按值值从小到大顺序。

  

<强> ComandLineRunner和ApplicationRunner区别和使用
  

  

如果需要在springapplication启动之后运行一些特定的代码,可以实现ApplicationRunner或
  CommandLineRunner接口。两个接口以相同的方式工作,并提供了一& # 8203;& # 8203;个单一的运行方法,该方法将被调用
  SpringApplication.run(…& # 8203;)完成之前。

  

这两个接口的不同之处在于:ApplicationRunner中运行方法的参数为ApplicationArguments,而CommandLineRunner接口中运行方法的参数为字符串数组。

  

以上所述是小编给大家介绍的弹簧引导启动加载数据原理分析,希望对大家有所帮助,如果大家有任何疑问请给我留的言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!

弹簧引导启动加载数据原理分析