JAX-RS 是否支持验证组?
Will JAX-RS support validation groups?
来自 JSR-339:
For simplicity, JAX-RS implementations are NOT REQUIRED to support processing groups other than Default.
这严重限制了 JAX-RS 中验证的实用性,因为例如创建和更新您通常使用相同的模型对象,但是对于创建不应提供对象的 ID,而对于更新则应提供 ID提供,可以使用验证组轻松验证。一般来说,在多个流程中使用的所有模型对象都无法验证。
我不理解简单性论点,因为 Bean Validation 已经支持组,所以 JAX-RS 实现只需要像 Hibernate Validator 一样将组传递给 Bean Validation 实现。
那么是否有计划向 JAX-RS 添加验证组?
事实证明它确实支持验证组。来自同一个 JSR-339:
The presence of @Valid will trigger validation of all the constraint annotations decorating a Java bean class. This validation will take place in the Default processing group unless the @ConvertGroup annotation is present.
例如,这是在我的自定义 Create
或 Update
组而不是 Default
组中验证帐户 bean 的方法:
@POST
@Consumes(MediaType.APPLICATION_JSON)
Response createAccount(@Valid @ConvertGroup(from = Default.class, to = Create.class)
Account account)
@POST
@Consumes(MediaType.APPLICATION_JSON)
Response updateAccount(@Valid @ConvertGroup(from = Default.class, to = Update.class)
Account account)
public class Account {
@Null(groups = Create.class)
@NotNull(groups = Update.class)
private String Id;
}
public interface Create {}
public interface Update {}
来自 JSR-339:
For simplicity, JAX-RS implementations are NOT REQUIRED to support processing groups other than Default.
这严重限制了 JAX-RS 中验证的实用性,因为例如创建和更新您通常使用相同的模型对象,但是对于创建不应提供对象的 ID,而对于更新则应提供 ID提供,可以使用验证组轻松验证。一般来说,在多个流程中使用的所有模型对象都无法验证。
我不理解简单性论点,因为 Bean Validation 已经支持组,所以 JAX-RS 实现只需要像 Hibernate Validator 一样将组传递给 Bean Validation 实现。
那么是否有计划向 JAX-RS 添加验证组?
事实证明它确实支持验证组。来自同一个 JSR-339:
The presence of @Valid will trigger validation of all the constraint annotations decorating a Java bean class. This validation will take place in the Default processing group unless the @ConvertGroup annotation is present.
例如,这是在我的自定义 Create
或 Update
组而不是 Default
组中验证帐户 bean 的方法:
@POST
@Consumes(MediaType.APPLICATION_JSON)
Response createAccount(@Valid @ConvertGroup(from = Default.class, to = Create.class)
Account account)
@POST
@Consumes(MediaType.APPLICATION_JSON)
Response updateAccount(@Valid @ConvertGroup(from = Default.class, to = Update.class)
Account account)
public class Account {
@Null(groups = Create.class)
@NotNull(groups = Update.class)
private String Id;
}
public interface Create {}
public interface Update {}