Spring Boot メインクラスから他のクラスを呼び出す方法
Spring BootはAPIや画面からの呼び出し等のWebアプリケーションが主流である
画面やWebを意識しないバッチ処理等を行いたい場合にメインクラスから他のクラスを呼び出す方法としては下記の方法がある
今回は②の実装方法を解説する
①JavaConfigで定義ファイルを作成し、他クラスを呼び出す方法
実装方法はこちら ⇒ Bean定義ファイルの作成方法(JavaConfig)
②CommandLineRunnerインターフェースを実装し、runメソッドをOverrideして、他クラスを呼び出す方法
■事前準備
SampleControllerクラスを用意する
package com.example.Controllers;
public class SampleController {
public String mainRun() {
// CSVファイル読み込み
var res = "SampleControllerをBeanで呼び出すテスト";
return res;
}
}
■メインクラスにCommandLineRunnerインターフェース実装して、他のクラスを呼び出す
@SpringBootApplication
// CommandLineRunnerインターフェースを実装
public class SampleApplication implements CommandLineRunner {
// SampleControllerクラスをDI
@Autowired
SampleController sampleControlelr;
// CommandLineRunnerクラスからOverrideする事により、AutowiredアノテーションでDIが可能になる
// パラメーターが「--○○」のような形でもパラメーターとして認識することに注意
@Override
public void run(String... strings) {
// AutowiredアノテーションでDIしているのでSampleControllerクラスのmainRunメソッドを呼び出す事ができる
var res = sampleControlelr.mainRun();
SampleApplication
}
public static void main(String[] args) {
SpringApplication.run(SampleApplication.class, args);
}