<JavaLearn/>
Spring Boot レッスン2

アノテーション

@Component、@Service、@Repository、@Controller、@Autowired

Springのステレオタイプアノテーション

Springではクラスの役割に応じたアノテーションを付けることで、DIコンテナに自動登録(Bean登録)されます。@Component が基本で、用途別に@Service@Repository@Controller が用意されています。

  • @Component - 汎用的なSpring管理Bean
  • @Service - ビジネスロジック層(意味的な区別)
  • @Repository - データアクセス層(例外変換機能あり)
  • @Controller / @RestController - Webリクエスト処理層
  • @Autowired - 依存オブジェクトの自動注入

ステレオタイプアノテーションの使い分け

各レイヤーに適切なアノテーションを付けることで、コードの意図が明確になり、 Spring固有の機能(例外変換など)も活用できます。

Javaエディタ

@Componentと派生アノテーション

@Component はすべてのステレオタイプアノテーションの親です。@Service@Repository は @Component のメタアノテーションを持つ特殊化されたバージョンです。

Javaエディタ