Spring 5.3 アノテーション@Componentを使用してHello Worldを表示するサンプル
環境
Spring 5.3.23
JDK8
Eclipse 4.14.0
操作方法
1.Mavenプロジェクトを作成します
1)Javaプロジェクトを右クリックします。
2)「構成」>「Mavenプロジェクトへ変換」をクリックします。
3)「グループId」と「アーティファクトId」を入力します。
4)プロジェクトにpom.xmlが追加されます。
2.pom.xml
以下のコードをpom.xmlの<project>タグ内に貼り付けます。
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.23</version>
</dependency>
</dependencies>
3.アプリケーションファイル(ArkgameApp.java)
package com.arkgame.test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ArkgameApp {
public static void main(String[] args) {
//applicationContext.xmlを読み込み
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext("applicationContext.xml");
//「クラス.class」を読み込み
UserService cft
= context.getBean(UserService.class);
System.out.println("名前: "+cft.getName());
context.close();
}
}
4.設定ファイル(applicationContext.xml)
XMLファイルにcomponent-scanと対象のパッケージを記述します。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- component-scan scanの対象を指定 -->
<context:component-scan base-package="com.arkgame.test" />
</beans>
5.UserService.java
対象のクラスに@Componetを追加します
package com.arkgame.test;
import org.springframework.stereotype.Component;
//アノテーション@Componetを追加
@Component
public class UserService {
public String getName() {
return "山田 太郎";
}
}
説明
public @interface ComponentScan
@Configuration クラスで使用するコンポーネントスキャンディレクティブを設定します。Spring XML の <context:component-scan> 要素と並行してサポートを提供します。 basePackageClasses() または basePackages()(またはその別名 value())のいずれかを指定して、スキャンする特定のパッケージを定義できます。特定のパッケージが定義されていない場合、このアノテーションを宣言するクラスのパッケージからスキャンが行われます。
6.動作確認
「ArkgameApp.java」を右クリックして「実行」->「Javaアプリケーション」をクリックするとコンソールに「名前: 山田 太郎」と表示されます。