In Jakarta Bean Validation, how do container-element constraints like List<@Email String> reach each element, and why might they never fire?
answer
- type argument, not the field
- an extractor opens the container
- Optional is not unwrapped by default
- null container skips element checks
- own wrapper needs a registered extractor
basics
~20 sConstraints on a type argument, like List<@Email String>, run per element because a ValueExtractor pulls each value out. They miss when written on the container instead, when the container is null, or when nothing cascades into the holder.
solid answer
~40 sA container-element constraint sits on the type argument, as in `List<@NotBlank @Email String>` or `Optional<@Size(max = 30) String>`, and Hibernate Validator applies it to each value a `ValueExtractor` pulls out; built-ins cover `Iterable`, `List`, `Map` keys and values, `Optional`, the primitive optionals and arrays. Of the standard-library extractors, only the `OptionalInt`, `OptionalLong` and `OptionalDouble` ones are `@UnwrapByDefault`, so `@NotNull Optional<String>` checks the `Optional` object itself and `@Email List<String>` throws `UnexpectedTypeException`. Element constraints are skipped when the list itself is `null`, and an empty `Optional` hands `null` to the constraint, which `@Email` accepts. A request that is a nested field, a list element or a Spring method parameter is only validated when that reference is marked `@Valid`. A custom generic wrapper needs its own `ValueExtractor`, registered through the service loader or `Configuration#addValueExtractor`.
code
java · 23 linesimport jakarta.validation.Valid;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import java.util.List;
import java.util.Optional;
public class SignupRequest {
// Broken: both constraints validate the containers, never the strings inside.
// @Size(min = 1) List<String> emails;
// @NotNull Optional<String> nickname;
@NotNull
@Size(min = 1)
private List<@NotBlank @Email String> emails;
@NotNull
private Optional<@Size(min = 2, max = 30) String> nickname = Optional.empty();
private List<@Valid Referral> referrals = List.of();
}go deeper
Recall that a constraint inside the angle brackets, such as List<@Email String>, checks every element, while one on the field checks the list itself.
Explain value extractors: built-ins for Iterable, List, Map keys and values, Optional and arrays; of the java.util ones only the primitive-optional extractors unwrap by default; null containers skip element checks.
Diagnose element rules that let bad data through: a constraint on the wrapper, a null container, @Email accepting blanks, a missing @Valid cascade, or an unregistered extractor for an in-house wrapper.
Decide where element-level rules live for shared request types and whether in-house wrapper types are worth a registered extractor or should be replaced by standard containers the validator already understands.
## What a container-element constraint is A **container-element constraint** is a Jakarta Bean Validation constraint written on a **type argument** instead of on the field or parameter itself: `List<@NotBlank @Email String> emails`, `Map<@NotBlank String, @Positive Integer> quotas`, `Optional<@Size(max = 30) String> nickname`. It says "every value inside this container must satisfy the rule", not "the container must satisfy the rule". The constraint annotation must allow `ElementType.TYPE_USE` in its `@Target`; every built-in Jakarta Validation constraint does, so a custom constraint is the only place this needs checking (the compiler rejects a misplaced annotation). Before Hibernate Validator 6 a subset of this needed `@Valid` on the container to switch it on. That is no longer required: a type-argument constraint is validated on its own whenever the enclosing object is validated. ## How the engine reaches the elements: value extractors The validator does not know how to open a `List` or an `Optional` by itself. It asks a **`ValueExtractor`** (`jakarta.validation.valueextraction.ValueExtractor<T>`), an object with one method, `extractValues(T originalValue, ValueReceiver receiver)`, that hands each contained value to a receiver: - `value()` for a pure wrapper such as `Optional` (no extra path node, so a violation reads as if it were on the property); - `indexedValue()` for a `List` (the path shows `<list element>` and the index); - `iterableValue()` for a plain `Iterable` such as a `Set`; - `keyedValue()` for a `Map`, used by two separate extractors, one for keys (`<map key>`) and one for values (`<map value>`). Hibernate Validator ships built-in extractors for `Iterable`, `List`, `Map` keys and values, `Optional`, `OptionalInt`, `OptionalLong`, `OptionalDouble`, object and primitive arrays, and the JavaFX observable types when JavaFX is on the classpath. For a type-argument constraint the extractor is chosen from the **declared** type; for cascaded validation it is chosen from the **runtime** type of the value. ## Constraint on the container vs on its elements Whether a constraint written on the field itself is "unwrapped" depends on one marker, **`@UnwrapByDefault`**, placed on an extractor class. Among the built-ins it is on the `OptionalInt`, `OptionalLong` and `OptionalDouble` extractors and on the JavaFX `ObservableValue` one, and **not** on the `List`, `Map` or `Optional` ones. | Declaration | What is validated | |---|---| | `List<@Email String> emails` | each element | | `@Size(min = 1) List<String> emails` | the list (its size) | | `@Email List<String> emails` | the list: no `@Email` validator for `List`, so validation throws `UnexpectedTypeException` | | `@NotNull Optional<String> nickname` | the `Optional` reference; `Optional.empty()` passes | | `Optional<@NotBlank String> nickname` | the wrapped value; an empty `Optional` hands it `null` | | `@Min(1) OptionalInt retries` | the wrapped `int`, because that extractor is `@UnwrapByDefault` | A constraint's `payload` can override the default per declaration: `Unwrapping.Unwrap` forces unwrapping, `Unwrapping.Skip` keeps the constraint on the container. ## Why the element constraints "never fire" Take a service that validates a sign-up request holding a list of emails and an optional nickname, and finds bad addresses getting through. The usual causes, roughly in order of frequency: 1. **The constraint is on the container.** `@NotNull Optional<String>` or `@Size List<String>` checks the wrapper only. Move string rules onto the type argument. 2. **The container is `null`.** When the list or the `Optional` field itself is `null`, Hibernate Validator skips the element constraints entirely. Add `@NotNull` on the field if absence is an error. 3. **The rule accepts the value by design.** `@Email` treats `null` and the empty string as valid, so an empty `Optional<@Email String>` and a list element `""` both pass. Pair it with `@NotBlank` where blank is wrong; do not put `@NotBlank` inside an `Optional` you allow to be empty, because the empty case then fails. 4. **Nothing cascades into the request.** If the request is a field of another object, a list element (`List<SignupRequest>`) or a method parameter under Spring method validation, its own constraints run only when that reference is marked `@Valid`, for example `List<@Valid SignupRequest>`. The older `@Valid List<SignupRequest>` form still works but is not recommended. ## Custom wrapper types A type argument on your own generic wrapper (say `Maybe<@Email String>`) has no built-in extractor, so building that class's constraint metadata fails with a `ConstraintDeclarationException` ("No value extractor found for type parameter"). Implement one and register it: ```java public class MaybeValueExtractor implements ValueExtractor<Maybe<@ExtractedValue ?>> { @Override public void extractValues(Maybe<?> originalValue, ValueReceiver receiver) { receiver.value(null, originalValue.orElseNull()); } } ``` Hibernate Validator does not scan for extractors. Registration options, from lowest to highest priority: - a `META-INF/services/jakarta.validation.valueextraction.ValueExtractor` file listing the class; - the `META-INF/validation.xml` configuration; - `Configuration#addValueExtractor(...)` at bootstrap; in Spring this is `LocalValidatorFactoryBean.setConfigurationInitializer(...)`, and Spring Boot applies every `ValidationConfigurationCustomizer` bean through it; - `ValidatorContext#addValueExtractor(...)` for a single `Validator` instance. A higher-priority extractor for the same type and type parameter replaces a lower one, which is also how you would override a built-in.
- How do you make a constraint written on an Optional field apply to the wrapped value without moving it to the type argument?Add the `Unwrapping.Unwrap` payload, as in `@Email(payload = Unwrapping.Unwrap.class) Optional<String> nickname`; Hibernate Validator then requires exactly one maximally specific extractor for the declared type and validates the extracted value. The opposite payload, `Unwrapping.Skip`, keeps a constraint on the container even when its extractor is `@UnwrapByDefault`, such as `OptionalInt`. Writing `Optional<@Email String>` is usually clearer.
- Is the value extractor chosen from the declared type or the runtime type?For a container-element constraint, from the declared type: a field declared as `Collection<@Email String>` uses the `Iterable` extractor whatever list class it holds. For cascaded validation (`@Valid` on a container element), Hibernate Validator narrows to an extractor compliant with the runtime class of the value and throws a `ConstraintDeclarationException` if none fits.
- How are violations on Map keys and values told apart in the result?Two extractors read a `Map`: one passes keys, one passes values, both through `keyedValue()`. The violation's property path gets a container-element node named `<map key>` or `<map value>` and carries the entry's key, so a client can tell which entry failed and on which side. List elements get `<list element>` with the index.
Think of a customs check: a rule stuck on the suitcase checks the suitcase, a rule on its contents makes the officer open it, and the officer only knows how to open luggage types someone has trained them on. A value extractor is that training; Optional is a bag they check from the outside unless told to open it.
- Putting @Email on a List<String> field validates each string in the list.
- Hibernate Validator unwraps Optional by default, so @NotNull Optional<String> rejects an empty Optional.
- Element constraints only run if the container field is also annotated with @Valid.
- A null list fails List<@NotBlank String> because the element constraint sees null.
- An in-house generic wrapper type supports container-element constraints without registering any extractor.
- @Email rejects empty strings, so @NotBlank is redundant next to it.