「Spring 5.3.21」@Configurationと@ComponentでHello Worldを表示する方法
環境
Spring 5.3.21
Java 17
Eclipse IDE 2022-06 M2 (4.24.0 M2)
構文
1.@Configuration
public class クラス名{コード}
クラスが 1 つ以上の @Bean メソッドを宣言し、Spring コンテナーによって処理されて、実行時にこれらの Bean の Bean 定義とサービスリクエストを生成できることを示します。
2.AnnotationConfigApplicationContext
@Configuration クラスは通常、AnnotationConfigApplicationContext またはその Web 対応バリアント AnnotationConfigWebApplicationContext を使用してブートストラップされます。
操作方法
1.pom.xmlに依存関係spring 5.3.21のjarをインストールします
以下の内容を編集します
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.21</version>
</dependency>
</dependencies>
2.実行ファイル(TestApp.java)の作成
package com.arkgame.study;
import org.springframework.beans.BeansException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class TestApp {
public static void main(String[] args) {
//DIコンテナを生成
try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ArkConfig.class)) {
//DIコンテナからbeanインスタンスを取得
User user = context.getBean(User.class);
System.out.println("名前: " + user.getName());
} catch (BeansException e) {
e.printStackTrace();
}
}
}
3.@Configurationを利用して指定した配下のクラスを設定します。
package com.arkgame.study;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
//設定クラス
@Configuration
//scanの対象になる
@ComponentScan("com.arkgame.study")
public class ArkConfig {
}
4.@Componentで追加したBeanクラスの作成
package com.arkgame.study;
import org.springframework.stereotype.Component;
@Component
public class User { //BeanとしてDIコンテナに登録
public String getName() {
return "山田 太郎";
}
}
5.動作確認
「TestApp.java」を右クリックして実行(R)->「Javaアプリケーション」をクリックします。 「名前: 山田太郎」が表示されます。