0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【保存版】Spring Bootでよく使うアノテーション総まとめ - 概要とコードサンプル付き

0
Last updated at Posted at 2025-11-15

はじめに

Spring Bootを使った開発では、数多くのアノテーションが登場します。本記事では、実務で頻出するアノテーションをカテゴリ別に整理し、概要とコードサンプルをまとめました。リファレンスとしてご活用ください。

対象バージョン: Spring Boot 3.x / Spring Framework 6.x


1. アプリケーション起動・設定系

@SpringBootApplication

Spring Bootアプリのエントリーポイント。@Configuration + @EnableAutoConfiguration + @ComponentScan をまとめたメタアノテーション。

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

@Configuration

Beanを定義する設定クラスであることを示す。

@Configuration
public class AppConfig {
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

@Bean

メソッドの戻り値をSpringコンテナに登録する。ライブラリ由来のクラスなど、自分でアノテーションを付与できないクラスをBean化するのに有用。

@ComponentScan

指定パッケージ配下のコンポーネントを自動検出する。

@ComponentScan(basePackages = "com.example.myapp")

@EnableAutoConfiguration

クラスパスに基づいてBeanを自動設定する。通常は@SpringBootApplication経由で暗黙的に有効化される。

@PropertySource

外部プロパティファイルを読み込む。

@Configuration
@PropertySource("classpath:custom.properties")
public class CustomConfig {}

2. DIコンテナ・コンポーネント系

@Component

汎用的なBean登録アノテーション。下記3つはすべて@Componentの特殊化。

@Service

ビジネスロジック層のBeanを示す。

@Service
public class UserService {
    public User findById(Long id) { /* ... */ }
}

@Repository

データアクセス層のBeanを示す。永続化関連の例外をDataAccessExceptionに変換する効果もある。

@Repository
public interface UserRepository extends JpaRepository<User, Long> {}

@Controller / @RestController

Webリクエストを処理するコントローラー。@RestController@Controller + @ResponseBodyで、JSON/XML APIで定番。

@RestController
@RequestMapping("/api/users")
public class UserController { /* ... */ }

@Autowired

依存性を自動注入する。コンストラクタが1つしかない場合は省略可能(推奨はコンストラクタインジェクション)。

@Service
public class OrderService {
    private final UserService userService;

    public OrderService(UserService userService) {
        this.userService = userService;
    }
}

@Qualifier

同じ型のBeanが複数ある場合に、注入対象を指定する。

@Autowired
@Qualifier("mysqlDataSource")
private DataSource dataSource;

@Value

プロパティ値を注入する。

@Value("${app.api.key}")
private String apiKey;

@ConfigurationProperties

プロパティをクラスにバインドする。型安全で、複数プロパティを扱う場合に推奨。

💡 Tips: @ConfigurationPropertiesScan を使った一括スキャン
サンプルのように @Component を付与して個別にBean化する手法のほか、Spring Boot 2.2以降ではメインクラス等に @ConfigurationPropertiesScan を付与し、対象クラスを一括で読み込む設計も主流です。この場合、プロパティクラス側の @Component は不要になります。

@Component
@ConfigurationProperties(prefix = "app.mail")
public class MailProperties {
    private String host;
    private int port;
    // getter/setter
}

@Primary

同型Beanが複数存在する場合に、優先的に注入されるBeanを指定。

@Scope

Beanのスコープを指定(singleton, prototype, request, session など)。

@Component
@Scope("prototype")
public class TaskRunner {}

3. Web・REST系

@RequestMapping

URLとHTTPメソッドをマッピング。クラス/メソッドいずれにも付与可能。

@GetMapping / @PostMapping / @PutMapping / @DeleteMapping / @PatchMapping

HTTPメソッド特化版。可読性のためこちらが推奨。

@RestController
@RequestMapping("/api/users")
public class UserController {
    @GetMapping("/{id}")
    public User get(@PathVariable Long id) { /* ... */ }

    @PostMapping
    public User create(@RequestBody @Valid UserForm form) { /* ... */ }
}

@PathVariable

URLパスの変数をバインド。

@RequestParam

クエリパラメータやフォームパラメータをバインド。

@GetMapping("/search")
public List<User> search(@RequestParam(defaultValue = "") String keyword) { /* ... */ }

@RequestBody

HTTPリクエストボディ(JSON等)をオブジェクトにマッピング。

@ResponseBody

メソッドの戻り値をHTTPレスポンスボディとして返す。@RestControllerなら不要。

@ResponseStatus

レスポンスステータスコードを指定。

@ResponseStatus(HttpStatus.CREATED)
@PostMapping
public User create(@RequestBody UserForm form) { /* ... */ }

@RequestHeader / @CookieValue

ヘッダー・Cookieの値をバインド。

@ExceptionHandler / @ControllerAdvice

例外ハンドリングを集約。

@RestControllerAdvice // APIの場合は @ResponseBody の効果を内包した @RestControllerAdvice を使用します
public class GlobalExceptionHandler {
    @ExceptionHandler(EntityNotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ErrorResponse handleNotFound(EntityNotFoundException e) {
        return new ErrorResponse(e.getMessage());
    }
}

@CrossOrigin

CORS設定を行う。


4. データアクセス・JPA系

Spring Boot 3.xでは、JPAやバリデーションのアノテーションのimport元が javax.* から jakarta.* に変更されています。

@Entity

JPAエンティティクラスを示す。

@Entity
@Table(name = "users")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false, length = 100)
    private String name;
}

@Table / @Column

テーブル名・カラム名の明示。

@Id / @GeneratedValue

主キーと採番戦略。

@OneToMany / @ManyToOne / @OneToOne / @ManyToMany

エンティティ間のリレーション。

@Entity
public class Order {
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id")
    private User user;
}

@Transactional

トランザクション境界を宣言。Service層に付与するのが一般的。

@Service
public class PaymentService {
    @Transactional
    public void transfer(Long fromId, Long toId, BigDecimal amount) { /* ... */ }
}

@Query

JPQLやネイティブSQLを直接記述。

public interface UserRepository extends JpaRepository<User, Long> {
    @Query("SELECT u FROM User u WHERE u.email = :email")
    Optional<User> findByEmail(@Param("email") String email);
}

@Modifying

更新系クエリに必須。


5. バリデーション系

@Valid / @Validated

入力値の検証をトリガー。@Validatedはグループ指定が可能。

@PostMapping
public User create(@RequestBody @Valid UserForm form) { /* ... */ }

代表的な制約アノテーション

アノテーション 概要
@NotNull null不可
@NotBlank null/空文字/空白不可(String)
@NotEmpty null/空不可(Collection/String)
@Size(min, max) サイズ範囲
@Min / @Max 数値範囲
@Email メール形式
@Pattern 正規表現
public class UserForm {
    @NotBlank
    @Size(max = 50)
    private String name;

    @NotBlank
    @Email
    private String email;
}

6. テスト系

@SpringBootTest

アプリケーションコンテキスト全体をロードする統合テスト用。

@SpringBootTest
class ApplicationTests {
    @Test
    void contextLoads() {}
}

@WebMvcTest

Controller層のみをテスト(軽量)。

@WebMvcTest(UserController.class)
class UserControllerTest {
    @Autowired MockMvc mockMvc;
    @MockBean UserService userService;
}

@DataJpaTest

JPA関連のみをテスト。インメモリDBで動作。

@MockitoBean / @MockitoSpyBean ( @MockBean / @SpyBean )

Spring管理下のBeanをモック/スパイに差し替え。
※Spring Boot 3.4以降は @MockitoBean / @MockitoSpyBean への移行が推奨されています

@TestConfiguration

テスト専用のBean定義クラス。


7. AOP・その他

@Aspect

AOPのアスペクトクラスを示す。

@Aspect
@Component
public class LoggingAspect {
    @Around("execution(* com.example.service..*(..))")
    public Object logExecution(ProceedingJoinPoint pjp) throws Throwable {
        long start = System.currentTimeMillis();
        Object result = pjp.proceed();
        System.out.println("Elapsed: " + (System.currentTimeMillis() - start) + "ms");
        return result;
    }
}

@Scheduled

定期実行。@EnableSchedulingと併用。

@Scheduled(cron = "0 0 3 * * *")
public void dailyBatch() { /* ... */ }

@Async

非同期実行。@EnableAsyncと併用。

@Conditional

条件付きでBeanを登録する。@ConditionalOnProperty, @ConditionalOnClass, @ConditionalOnMissingBean など、自動設定の基盤。

@Bean
@ConditionalOnProperty(name = "feature.new-api.enabled", havingValue = "true")
public NewApiClient newApiClient() { /* ... */ }

@Profile

プロファイルごとにBeanを切り替え。

@Service
@Profile("dev")
public class MockPaymentService implements PaymentService {}

まとめ

Spring Bootのアノテーションは数が多いですが、**「設定系」「DI系」「Web系」「データ系」「テスト系」**のカテゴリに整理して覚えるとスッキリします。特に以下は必ず押さえておきたいアノテーションです。

  • @SpringBootApplication / @Configuration / @Bean
  • @Service / @Repository / @RestController
  • @GetMapping / @PostMapping / @RequestBody / @PathVariable
  • @Entity / @Transactional / @Query
  • @Valid / @NotBlank など
  • @SpringBootTest / @WebMvcTest / @MockBean

本記事がリファレンスとして役立てば幸いです。コメントで「このアノテーションも追加して!」等あればぜひお知らせください。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?