Spring MVC 5.3 アノテーション@Componentでコンストラクタを実行するサンプル

環境
Spring 5.3.23
JDK8
Eclipse 4.14.0

構文
@Compnentは、Spring BootでWebのMVCアプリを作成するときに使用する@Controller, @Service, @Repositoryと同様に、
SpringのDIコンテナに管理させて@AutowireなどでDIできるようにしたいクラスにつけます。
書式
@Component
public class クラス名 {処理コード}

操作方法
1.実行ファイル(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");

            // 対象クラスを取得
            UserService cft = context.getBean(UserService.class);
            // getUserメソッドを呼び出す
            System.out.println("情報: " + cft.getUser());
            context.close();

      }

}

説明
new ClassPathXmlApplicationContext(“applicationContext.xml");

applicationContext.xmlを読み込みます。
クラス名 インスタンス名 =context.getBean(クラス名.class)

2.UserServiceクラスの定義(UserService.java)

package com.arkgame.test;

import org.springframework.stereotype.Component;

//アノテーション@Componetを追加
@Component
public class UserService {

      // クラスUserのインスタンス
      User user;

      /** クラスのコンストラクタ */
      public UserService(User user) {
            this.user = user;
      }
      
      /**
       *  ユーザー情報を取得します。
       *  
       * @return
       */
      public String getUser() {
            // インスタンスuserの関数を呼び出す
            return user.geUserName();
      }
}

3.Userクラスの定義(User.java)

package com.arkgame.test;

import org.springframework.stereotype.Component;

//アノテーション@Componentの追加
@Component
public class User {

      /**
       * ユーザー名を取得します。
       * 
       * @return ユーザー名
       */
      public String geUserName() {
            return "テスト 太郎";
      }
}

Userクラスにアノテーション@Componentを追加します。

4.設定ファイル(applicationContext.xml)

<?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で対象パッケージ名を指定 -->
      <context:component-scan
            base-package="com.arkgame.test" />
</beans>

説明

<context:component-scan base-package="パッケージ名" />
component-scanは、指定した配下がscanの対象になります。

5.実行確認

「ArkgameApp.java」を右クリックして「実行」->「Javaアプリケーション」をクリックするとコンソールに「情報: テスト 太郎」と表示されます。

 

SpringMVC

Posted by arkgame