是否可以在 JAX-RS 资源上有效地使用 JSR303(Bean Validation)注解?
因此,例如,如果我有一个已注释 @NotEmpty 的资源成员,如果不满足此约束,是否会向客户端生成一个错误?
这似乎是显而易见的事情,但也很高兴被告知更好的方法(我不想将验证移至 ORM/数据库级别)
是否可以在 JAX-RS 资源上有效地使用 JSR303(Bean Validation)注解?
因此,例如,如果我有一个已注释 @NotEmpty 的资源成员,如果不满足此约束,是否会向客户端生成一个错误?
这似乎是显而易见的事情,但也很高兴被告知更好的方法(我不想将验证移至 ORM/数据库级别)
Do you really mean validating the resource members? Usually the resource members are injected in this way or another (it's either contexts, or entity, or path/query/matrix params), as long as the JAX-RS framework works you'll get these members properly injected.
Personally I think it makes more sense to validate the entity since it has arrived by the wire, filled by a MessageBodyReader and basically you have no idea what's inside, right?
So if you decide to validate the entities, there are several approaches that you can take:
AFAIK, Apache Wink does not support built-in validations. You can implement a handler. See DeploymentConfiguration.initRequestHandlersChain()
. It supports adding user handlers. In your handler you can perform any validations. I even think that the Wink community will be glad if you contribute this code.
The only problem with this approach - it's bound to the Apache Wink. It won't work if you decide to move to a different JAX-RS framework.
Another approach is to make this validation in your own MessageBodyReader
. All you need to do is registering a special reader for your entities and validate the entity inside. You can still take advantage of standard MessageBodyReaders (like JAXB or Jackson) by using @Context Providers.getMessageBodyReader()
. The good part of this approach that it's standard JAX-RS. The bad that you use MessageBodyReaders for something they were not designed to.
The simplest approach is to validate the entity in first line of each resource method. It will create some code duplication, but sometimes simplicity wins.
一种解决方案 - 当我使用 Spring 2.5.x 时,我可以创建一个实现 InitializingBean 并委托给 Hibernate 的验证器的包装器类。它有效 - 有更好的解决方案吗?