gpt4 book ai didi

java - 使用 validator 依赖项注入(inject)配置自定义验证

转载 作者:行者123 更新时间:2023-12-02 12:21:37 26 4
gpt4 key购买 nike

我正在尝试使用 Hibernate Validation 6.0.1 定义约束定义,其中 validator 位于相对于约束注释的不同位置 (.jar/project)。又名,我想要验证的对象位于带有注释定义的项目“api”中,但我将在项目“modules/common”中拥有 validator

我正在遵循 the documentation 中的描述.

配置文件

@Bean
public Validator validator() {

HibernateValidatorConfiguration configuration = Validation
.byProvider( HibernateValidator.class )
.configure();

ConstraintMapping constraintMapping = configuration.createConstraintMapping();

constraintMapping
.constraintDefinition(ValidationComplexePerson.class)
.validatedBy(ValidationComplexePersonValidator.class);

return configuration.addMapping( constraintMapping )
.buildValidatorFactory()
.getValidator();

约束注释

@Documented
@Constraint(validatedBy = { })
@Target({TYPE, ANNOTATION_TYPE})
@Retention(RUNTIME)
public @interface ValidationComplexePerson {
...}

validator

public class ValidationComplexePersonValidator 
implements ConstraintValidator<ValidationComplexePerson, Personne> {

@Override
public void initialize(ValidationComplexePerson constraintAnnotation) {
}

@Override public boolean isValid(
Personne personne,
ConstraintValidatorContext constraintValidatorContext) {
if (personne.nom.matches(".*\\d+.*")) {
return false;
}
return true;
}

我的问题我遇到的问题是,如果我不在注释中添加“@Constraint(validatedby={})”,则会收到错误

HV000116: The annotation type must be annotated with @javax.validation.Constraint when creating a constraint definition.

当到达 Bean 配置中的“.constraintDefinition”时。

另一方面,如果我输入“@Constraint(validatedby={})”,我会得到

Error:(17, 1) java: For non-composed constraints a validator implementation must be specified using @Constraint#validatedBy().

对此解决方案可能会出现什么问题或替代方案有什么建议吗?

我还尝试了所提供的程序 here .

最佳答案

我怀疑您正在使用注释处理器,因为您的第二个错误来自它?

问题是在这种情况下注释处理器检查不正确。我认为我们应该删除它,因为无法使此检查与编程 API 一起工作。

现在只需删除注释处理器,它应该可以正常工作。

我打开了https://hibernate.atlassian.net/browse/HV-1470跟踪此问题。

关于java - 使用 validator 依赖项注入(inject)配置自定义验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45740148/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com