springbootのCommandLineRunnerインターフェースは、起動後にカスタムコードを実行する機能を実装します

CommandLineRunnerインターフェースのAPI:

import org.springframework.core.annotation.Order;
public interface CommandLineRunner {
    
    
    /**
     * Callback used to run the bean.
     * @param args incoming main method arguments
     * @throws Exception on error
     */
    void run(String... args) throws Exception;
}

開発では、プロジェクトの開始後に実装する必要のある関数があります。SpringBootが提供する簡単な実装ソリューションは、モデルを追加してCommandLineRunnerインターフェイスを実装することで、関数を実装するコードは実装されたrunメソッドに配置されます。
具体的な実装は次のとおりです。

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class MyStartupRunner implements CommandLineRunner{
    
    
    @Override
    public void run(String... args) throws Exception {
    
    
        System.out.println(">>>>>>>>>>>>>>>服务启动执行,执行加载数据等操作<<<<<<<<<<<<<");
    }
}

CommandLineRunnerインターフェイスを実装するクラスが複数ある場合、順序を確認する方法:
プロジェクトの開始後、SpringBootはCommandLineRunnerを実装するすべてのエンティティクラスをトラバースし、runメソッドを実行します。特定の順序で実行する必要がある場合は、エンティティクラスのOrderアノテーション[@Order(value = 1 ...)]で@を使用する(またはOrderインターフェイスを実装する)必要があります。次の2つの例を見てください

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

@Component
@Order(value=1)
public class MyStartupRunnerOne implements CommandLineRunner{
    
    
    @Override
    public void run(String... args) throws Exception {
    
    
        System.out.println(">>>>>>>>>>>>>>>服务启动第一个开始执行的任务,执行加载数据等操作<<<<<<<<<<<<<");
    }
}
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Order(value=2)
public class MyStartupRunnerTwo implements CommandLineRunner{
    
    
    @Override
    public void run(String... args) throws Exception {
    
    
        System.out.println(">>>>>>>>>>>>>>>服务第二顺序启动执行,执行加载数据等操作<<<<<<<<<<<<<");
    }
}

@orderアノテーションは、上記の2つの例のロード順序と開始順序の定義を実現するために使用されます。

おすすめ

転載: blog.csdn.net/u011930054/article/details/107034902