Springのアノテーションのメモ。
|
|
Springではアノテーションを多用するので、よく見かけるアノテーションを調べてみた。
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;
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;
なお、JPAのEntityManagerを取得したい場合は、@PersistenceContextアノテーションを使う。[2017-10-11]
import javax.persistence.EntityManager; import javax.persistence.PersistenceContext;
@PersistenceContext private EntityManager entityManager;
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アノテーションもシングルトンインスタンスを作るものだが、あちらはメソッドに付ける)