欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

spring boot启动加载数据原理分析

程序员文章站 2024-02-28 23:46:04
实际应用中,我们会有在项目服务启动的时候就去加载一些数据或做一些事情这样的需求。 为了解决这样的问题,spring boot 为我们提供了一个方法,通过实现接口 comm...

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

为了解决这样的问题,spring boot 为我们提供了一个方法,通过实现接口 commandlinerunner 来实现。

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

indexstartuprunner.java类:

import org.springframework.boot.commandlinerunner;
import org.springframework.core.annotation.order;
import org.springframework.stereotype.component;
/**
 * 服务启动执行
 */
@component
@order(value=1)
public class indexstartuprunner implements commandlinerunner {
  @override
  public void run(string... args) throws exception {
    system.out.println("
indexstartuprunner 
>>>>>>>>>>>>>>>服务启动执行,执行加载数据等操作 <<<<<<<<<<<<<");
  }
}
indexstartuprunner2.java类:
import org.springframework.boot.commandlinerunner;
import org.springframework.core.annotation.order;
import org.springframework.stereotype.component;
/**
 * 服务启动执行
 */
@component
@order(value=2)
public class indexstartuprunner2 implements commandlinerunner {
  @override
  public void run(string... args) throws exception {
    system.out.println("
indexstartuprunner2 
>>>>>>>>>>>>>>>服务启动执行,执行加载数据等操作 <<<<<<<<<<<<<");
  }
}

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

>>>>>>>>>>>>>>>indexstartuprunner服务启动执行,执行加载数据等操作<<<<<<<<<<<<<
>>>>>>>>>>>>>>>indexstartuprunner2服务启动执行,执行加载数据等操作<<<<<<<<<<<<<

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

comandlinerunner和applicationrunner区别和使用

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

这两个接口的不同之处在于:applicationrunner中run方法的参数为applicationarguments,而commandlinerunner接口中run方法的参数为string数组。

以上所述是小编给大家介绍的spring boot启动加载数据原理分析,希望对大家有所帮助