[英]how to use Java validator annotations from constructor?
I have value object that holds String
. 我有持有String
值对象。 That String is subject to some restrictions (length, allowed characters, etc). 该字符串受到一些限制(长度,允许的字符等)。
I would like to use Java or Spring validation API for validating my object. 我想使用Java或Spring验证API来验证我的对象。 I would like to validate my domain object at creation time (in constructor). 我想在创建时(在构造函数中)验证我的域对象。
Sample code that realises that (validates this
using validation API): 实现此目的的示例代码(使用验证API this
进行验证):
void validate() {
LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean();
Set<ConstraintViolation<Msisdn>> violations = localValidatorFactoryBean.getValidator().validate(this);
if (!violations.isEmpty()) {
throw new ConstraintViolationException(violations);
}
}
I do not know how to get instance of javax.validation.Validator
from constructor. 我不知道如何从构造函数中获取javax.validation.Validator
实例。
In Spring-managed code (service) I could just @Autowire
instance of javax.validation.Validator
or org.springframework.validation.Validator
and it works. 在Spring管理的代码(服务)中,我可以只是javax.validation.Validator
或org.springframework.validation.Validator
@Autowire
实例,它可以正常工作。
But how to make it work outside of Spring-managed code (in constructor of value object, that stands on his own)? 但是如何使它在Spring托管代码之外(在value对象的构造函数中,独立存在)工作呢?
I know that I can write validation rules using ifs, but validation annotations makes code much simpler. 我知道我可以使用ifs编写验证规则,但是验证注释使代码更简单。
Hibernate Validator documentation describes how to get instance of javax.validation.Validator Hibernate Validator文档描述了如何获取javax.validation.Validator的实例
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
But it is not suitable to build ValidatorFactory
in constructor. 但是不适合在构造函数中构建ValidatorFactory
。 It is time-consuming operation. 这是耗时的操作。 Maybe using cached reference in thrad-local would help, but I do not like that increased complexity. 也许在thrad-local中使用缓存的引用会有所帮助,但是我不喜欢这种增加的复杂性。
Finally, I have decided to write validation rules for my value objects using Guava Preconditions 最后,我决定使用Guava前提条件为我的值对象编写验证规则。
Preconditions.checkNotNull(value, "value cannot be null");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.