0Pricing
Spring Boot 4 Microservices & REST APIs · レッスン

@ValidによるBean Validation

アノテーションでリクエストボディを検証します

「@ValidによるBean Validation」はCoddyKit上の無料Spring Boot 4 Microservices & REST APIsレッスンです。 これはレッスン1/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはSpring Boot 4 Microservices & REST APIs学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Spring Boot 4 Microservices & REST APIsコースには全4レッスンが含まれています。

このレッスンの一部はまだ翻訳されておらず、英語で表示されています。

Bean Validation Overview

Bean Validation (JSR-380, Jakarta Validation) lets you declare constraints with annotations on your DTO fields, then validate objects against them. Spring Boot integrates it so incoming request bodies are checked automatically.

Adding the Dependency

The validation API plus an implementation (Hibernate Validator) come via the validation starter. Adding it activates annotation-driven validation in controllers.

<!-- pom.xml -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

Constraints on a DTO

Annotate fields with constraints. Each describes a rule the value must satisfy, plus an optional message shown when it fails.

public class CreateUserRequest {
    @NotBlank
    private String name;
    @Email @NotNull
    private String email;
    @Size(min = 8, max = 64)
    private String password;
    @Min(18)
    private int age;
    // getters/setters
}

Common Constraints

The standard annotations cover most needs:

  • @NotNull — value must not be null
  • @NotBlank — string must contain non-whitespace
  • @NotEmpty — collection/string not empty
  • @Size, @Min, @Max, @Email, @Pattern

Triggering Validation with @Valid

In a controller, annotate the request body parameter with @Valid. Spring validates it before your method body runs; on failure it short-circuits with an error.

@PostMapping("/users")
public ResponseEntity<Void> create(@Valid @RequestBody CreateUserRequest req) {
    userService.create(req);
    return ResponseEntity.status(HttpStatus.CREATED).build();
}

What Happens on Failure

If validation fails, Spring throws MethodArgumentNotValidException for a @RequestBody. By default this yields a 400 Bad Request, so invalid input never reaches your service layer.

Custom Messages

Override the default message per constraint with the message attribute, or externalize messages for i18n via a resource bundle.

@Size(min = 8, message = "Password must be at least 8 characters")
private String password;

Validating Path and Query Params

To validate individual method parameters (not a DTO), put constraints directly on them and add @Validated at the class level so method-level validation is active.

@Validated
@RestController
public class ProductController {
    @GetMapping("/products")
    public List<Product> list(@RequestParam @Min(1) int page) {
        return service.page(page);
    }
}

Nested Validation

Validation does not automatically descend into nested objects. Mark the nested field with @Valid so its constraints are also checked.

public class OrderRequest {
    @NotNull
    @Valid
    private AddressDto shippingAddress;
    // ...
}

Validating Collections

To validate each element of a collection, place @Valid on the collection field; each item’s constraints are then evaluated.

public class CartRequest {
    @NotEmpty
    private List<@Valid LineItem> items;
    // ...
}

Validation Groups

Validation groups let the same DTO enforce different rules in different contexts (for example create vs update). Annotate constraints with a group interface and validate against that group.

public interface OnCreate {}

public class UserDto {
    @Null(groups = OnCreate.class)
    private Long id; // must be null when creating
}

Quick Check

Test your understanding of @Valid.

Recap

Bean Validation guards your input.

  • Add spring-boot-starter-validation
  • Declare constraints like @NotBlank, @Size, @Email on DTOs
  • Trigger with @Valid on request bodies; failures yield 400
  • Use @Validated for param-level validation
  • Nested objects and collections need their own @Valid

よくある質問

「@ValidによるBean Validation」レッスンは無料ですか?

はい。「@ValidによるBean Validation」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Spring Boot 4 Microservices & REST APIsコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Spring Boot 4 Microservices & REST APIsコースには全4レッスンが含まれています。

「@ValidによるBean Validation」で何を学びますか?

アノテーションでリクエストボディを検証します ブラウザで直接実行するハンズオンコードでSpring Boot 4 Microservices & REST APIsを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

Spring Boot 4 Microservices & REST APIsを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのSpring Boot 4 Microservices & REST APIsは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン1/4です。

「@ValidによるBean Validation」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このSpring Boot 4 Microservices & REST APIsレッスンでコードを書いて実行できますか?

はい。すべてのSpring Boot 4 Microservices & REST APIsレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. @ValidによるBean Validation
  2. カスタムバリデーター
  3. @ControllerAdviceと@ExceptionHandler
  4. Problem Details(RFC 7807)
← Spring Boot 4 Microservices & REST APIsに戻る