Springboot プロジェクトのスタートアップ初期化方法のいくつかの一般的な方法

説明

	在项目启动的过程中执行一些指定的业务逻辑代码,初始化数据,加载某一个配置文件等等,所有在项目启动过程中需要自动执行的业务。

シーン

開発中に遭遇したいくつかのシナリオを次に示します。

  1. プロジェクトが他のサービスを統合する場合、同僚は開始時にサービスを開始する必要があります (例: Netty サービス、ftp サービス構築など)。
  2. プロジェクトの開始時には、特定の情報項目の初期化や特定の情報項目の前処理など、初期設定が必要です。
  3. プロジェクトの起動では、他のシステムと対話したり、構成を読み取ったりする必要があります。

方法 1: ApplicationRunner インターフェイスを実装して run メソッドのロジックを書き直す

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
public class InitatialConfig implements ApplicationRunner {
    
    


    @Override
    public void run(ApplicationArguments args) throws Exception {
    
    
        System.out.println("项目启动初始化");
    }
}

ここに画像の説明を挿入

方法 2: CommandLineRunner インターフェイスを実装して run メソッドのロジックを書き直す

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

@Component
public class InitatialConfigCommand implements CommandLineRunner {
    
    



    @Override
    public void run(String... args) throws Exception {
    
    
        System.out.println("CommandLineRunner:"+"{}"+"接口实现方式重写");
    }
}

ここに画像の説明を挿入

方法 3: @PostConstruct アノテーションを使用する

    @PostConstruct
    public void testInitConfig(){
    
    

        System.out.println("@PostConstruct:"+"{}"+"注解方式实现启动初始化配置");
    }

ここに画像の説明を挿入

初期化シーケンス

  1. @PostConstruct アノテーションメソッド
  2. CommandLineRunner インターフェイスの実装
  3. ApplicationRunner インターフェースの実装

知らせ:

	当CommandLineRunner或者ApplicationRunner存在多个实现类的同时,可以使用@Order(1)注解进行顺序执行,该注解控制Bean的执行顺序。

おすすめ

転載: blog.csdn.net/A_awen/article/details/130647473