Bean定義ファイルの作成方法(JavaConfig)
DIコンテナにBeanを管理させる定義ファイル
■開発環境
OS:Windows
Java:Java11
IDE:Eclipse(ver:2019-06)
ビルドツール:Gradle
■JavaConfigの作成
JavaConfig用のクラスに「Configurationアノテーション」を付与する
今回、JavaConfigに設定するAppConfig.javaを作成する
更に「Beanアノテーション」を呼び出したいクラス型のメソッドに付与する
package com.example;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.example.Controllers.SampleController;
// JavaConfig用のクラスとして「@Configuration」を付与
@Configuration
public class AppConfig {
// SampleControllerというBeanをDIコンテナにsingletonで管理
@Bean
SampleController sampleController() {
return new SampleController();
}
}
■Beanで呼び出すクラスの作成
com.exampleパケージ配下に「Controllers」パケージを作成して、SampleControllers.javaを作成
package com.example.Controllers;
public class SampleController {
public String test() {
var res = "SampleControllerをBeanで呼び出すテスト";
return res;
}
}
■Beanの呼び出し
SampleController型のBeanを呼び出す
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Import;
import com.example.Controllers.SampleController;
@SpringBootApplication
// AppConfigクラスをインポート
@Import(AppConfig.class)
public class SampleApplication {
public static void main(String[] args) {
// DIコンテナ
ApplicationContext context = SpringApplication.run(SampleApplication.class, args);
// DIコンテナからSampleControllerのインスタンスを取得
SampleController sampleController = context.getBean(SampleController.class);
String res = sampleController.test();
System.out.print(res);
}
}