SpringBoot CommandLineRunner

x33g5p2x  于2021-03-14 发布在 Spring  
字(1.6k)|赞(0)|评价(0)|浏览(326)

CommandLineRunner接口可以实现当服务器启动时预先加载一些功能,比如参数预先加载等。当需要实现多个功能预先加载时,需要使用@Order来指定加载的顺序,它的源码如下:

public @interface Order {
    int value() default 2147483647; // 该值越小,则先被执行
}

使用步骤如下:
1. 创建SpringBoot项目
2. 创建三个类来实现CommandLineRunner接口
为了演示@Order的作用,创建如下三个Driver类。
com/example/clrunner/driver/CommandLineRunnerDriver1.java

package com.example.clrunner.driver;

import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Order(value = 1)
public class CommandLineRunnerDriver1 implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("CommandLineRunnerDriver1执行成功!");
    }
}

com/example/clrunner/driver/CommandLineRunnerDriver2.java

package com.example.clrunner.driver;

import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Order(value = 2)
public class CommandLineRunnerDriver2 implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("CommandLineRunnerDriver2执行成功");
    }
}

com/example/clrunner/driver/CommandLineRunnerDriver3.java

package com.example.clrunner.driver;

import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Order(value = 3)
public class CommandLineRunnerDriver3 implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("CommandLineRunnerDriver3执行成功!");
    }
}

3. 运行启动类,测试结果如下

相关文章

微信公众号

最新文章

更多