Spring MVC 5.3 アノテーション@Configurationと@ComponentScanを使用するサンプル
環境
Spring 5.3.23
JDK8
Eclipse 4.14.0
構文
@Configuration クラスで使用するコンポーネントスキャンディレクティブを設定します。
Spring XML の <context:component-scan> 要素と並行してサポートを提供します。
@ComponentScan を使用する場合、デフォルトのアノテーション設定処理(たとえば、@Autowired およびフレンドの処理)が想定されるためです。
操作方法
1.実行ファイル(ArkgameApp.java)
package com.arkgame.test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class ArkgameApp { public static void main(String[] args) { //設定ファイルからDIコンテナを生成 AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(UserConfig.class); // DIコンテナからbeanインスタンスを取得 UserService cft = context.getBean(UserService.class); // getUserメソッドを呼び出す System.out.println("名前: " + cft.getUser()); context.close(); } }
説明
設定ファイルからDIコンテナを生成
new AnnotationConfigApplicationContext(設定ファイル名.class);
DIコンテナからbeanインスタンスを取得します
context.getBean(クラス名.class);
2.UserServiceクラスの定義(UserService.java)
package com.arkgame.test; import org.springframework.stereotype.Component; //アノテーション@Componetを追加 @Component public class UserService { /** * ユーザー情報を取得します。 * * @return */ public String getUser() { // インスタンスuserの関数を呼び出す return "yamada 123456"; } }
3.設定ファイル(UserConfig.java)
package com.arkgame.test; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; // @CompoentScanで指定パッケージ名 @Configuration @ComponentScan("com.arkgame.test") public class UserConfig { }
説明
@Configurationは、設定クラスであることを示しています。 @ComponentScan(パッケージ名) component-scanで指定した配下の@Component等のアノテーションが付いたクラスがscanの対象になります。
4.動作確認
「ArkgameApp.java」を右クリックして「実行」->「Javaアプリケーション」をクリックするとコンソールに「名前: yamada 123456」と表示されます。