Spring Boot (教程九: 启动加载)

来源:互联网 发布:dos运行java程序 编辑:程序博客网 时间:2024/05/16 09:19

GitHub 地址:

https://github.com/asd821300801/Spring-Boot.git


CommandLineRunner 接口实现启动加载


需求:启动服务器的时候加载数据


- Spring Boot 提供 CommandLineRunner 接口,用于启动服务器的时候加载数据


用法很简单,只需要创建一个类,实现 CommandLineRunner 接口 ,重写 run(String… args) 方法即可


  • StartLoading.java

包所在:com.example.start



注意:创建的类属于Controller层,所以要加上@Component注解

package com.example.start;import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Controller;/** * 服务启动的时候运行 * 创建一个类实现 CommandLineRunner 接口,重写 run(String... arg0)方法 * @author LingDu */@Controllerpublic class StartLoading implements CommandLineRunner {    @Override    public void run(String... arg0) throws Exception {        System.out.println("StartLoading:服务启动的时候运行,正在加载数据。。。。。");    }}


执行结果:

1


  • StartLoading1.java

包所在:com.example.start



多个CommandLineRunner 实例优先级的问题

  • 使用@Order 注解设置Value值来执行顺序


作为演示,我们创建多一个类 StartLoading1.java ,实现CommandLineRunner接口并重写run(String… arg0)方法

  • 不同的是在:@Component 注解下添加 @Order(value=1)
package com.example.start;import org.springframework.boot.CommandLineRunner;import org.springframework.core.annotation.Order;import org.springframework.stereotype.Component;/** *  * @author LingDu */@Component@Order(value=1) //优先级 public class StartLoading1 implements CommandLineRunner {    @Override    public void run(String... arg0) throws Exception {        System.out.println("优先级:1 ********* StartLoading1:服务启动的时候运行,正在加载数据。。。。。");    }}


@Order 注解的执行优先级是按value值从小到大顺序。


2

原创粉丝点击