S-JIS[2017-08-27/2017-10-11] 変更履歴

Spring Frameworkのアノテーション

Springのアノテーションのメモ。


概要

Springではアノテーションを多用するので、よく見かけるアノテーションを調べてみた。


Bean

import org.springframework.context.annotation.Bean;

@Beanアノテーションは、シングルトンインスタンス(アプリケーション内で1つだけしかインスタンス化されない)を作るのに使うらしい。
@Beanアノテーションはメソッドにしか付けられない。

このシングルトンインスタンスを使う側は@Autowiredアノテーションを使用する。

例:

	@Bean
	public PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}


Spring FrameworkのDIコンテナーは、PasswordEncoderのシングルトンインスタンスとしてこのメソッドの戻り値を保持する

	// DIコンテナーが保持しているインスタンスがセットされる
	@Autowired
	private PasswordEncoder passwordEncoder;

Autowired

import org.springframework.beans.factory.annotation.Autowired;

@Autowiredアノテーションは、DIコンテナーが管理しているインスタンスを受け取る(インジェクション(注入)される)ものっぽい。

インスタンスは、@Beanアノテーションが付けられているメソッドや@Serviceアノテーション等が付けられているクラスから生成される。

例:

	@Bean
	public PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}

	@Autowired
	private PasswordEncoder passwordEncoder;

例:

@Service
public class LoginUserService implements UserDetailsService {
〜
}

	@Autowired
	private UserDetailsService userDetailsService;

PersistenceContext

なお、JPAのEntityManagerを取得したい場合は、@PersistenceContextアノテーションを使う。[2017-10-11]

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
	@PersistenceContext
	private EntityManager entityManager;

ComponentControllerServiceRepository

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

@Componentアノテーションを付けたクラスは「コンポーネント」として扱われる。
すなわち、DIコンテナーによってインスタンス化され、シングルトンインスタンスとして管理されるようになる、と思う。
(これにより、@Autowiredアノテーションでそのインスタンスを取得できる)

@Controller・@Service・@Repositoryは@Componentの特殊用途版。
@Controllerはコントローラー(画面遷移の制御)、@Serviceはサービス(ロジック)、@Repositoryはリポジトリー(データの永続化(DBアクセス) 用のインターフェース)に付ける。
@Beanアノテーションもシングルトンインスタンスを作るものだが、あちらはメソッドに付ける)


Spring Frameworkへ戻る / 技術メモへ戻る
メールの送信先:ひしだま