gpt4 book ai didi

java - 我可以更改方法参数的 ConstraintValidator 中的属性路径吗?

转载 作者:IT老高 更新时间:2023-10-28 20:35:24 24 4
gpt4 key购买 nike

如果您熟悉 Bean 验证框架,您就会知道无法获取方法参数的名称。因此,如果您对方法的第一个参数执行 @NotNull 约束并且验证失败,则 getPropertyPath 将类似于“arg1”。

我想创建自己的 @NotNull 版本,它可以取值,例如@NamedNotNull(“电子邮件地址”)。但我不知道如何在我的 validator 中覆盖#getPropertyPath?有什么办法可以做到这一点,还是我坚持使用“arg1”或“arg2”等。

编辑

根据我收到的答案,我能够提出以下实现,允许我从 @QueryParam 或 @PathParam 注释中获取值,并将它们用作 Bean Validation 注释(如 @NotNull)的属性路径。

对于 Jersey,您需要创建以下类。注意 DefaultParameterNameProvider 的实现:

public class ValidationConfigurationContextResolver implements ContextResolver<ValidationConfig> {
@Override
public ValidationConfig getContext( final Class<?> type ) {
final ValidationConfig config = new ValidationConfig();
config.parameterNameProvider( new RestAnnotationParameterNameProvider() );
return config;
}

static class RestAnnotationParameterNameProvider extends DefaultParameterNameProvider {

@Override
public List<String> getParameterNames( Method method ) {
Annotation[][] annotationsByParam = method.getParameterAnnotations();
List<String> names = new ArrayList<>( annotationsByParam.length );
for ( Annotation[] annotations : annotationsByParam ) {
String name = getParamName( annotations );
if ( name == null )
name = "arg" + ( names.size() + 1 );

names.add( name );
}

return names;
}

private static String getParamName( Annotation[] annotations ) {
for ( Annotation annotation : annotations ) {
if ( annotation.annotationType() == QueryParam.class ) {
return QueryParam.class.cast( annotation ).value();
}
else if ( annotation.annotationType() == PathParam.class ) {
return PathParam.class.cast( annotation ).value();
}
}

return null;
}
}
}

然后在您的 RestConfig 中,您需要添加以下行:

register( ValidationConfigurationContextResolver.class );

就是这样。现在您的 ConstraintValidationExceptions 将包含它们注释的 QueryParam 或 PathParam 的名称。例如:

 public void getUser( 
@NotNull @QueryParam( "emailAddress" ) String emailAddress,
@NotNull @QueryParam( "password" ) String password )
{ ... }

最佳答案

If you are familiar with the Bean Validation Framework you know that you cannot get the name of a method argument

这不太正确。 Bean Validation 指定了 ParameterNameProvider 的概念它允许您提供自己的实现。 Hibernate Validator 与 ParaNamer 集成提供参数名称。请参阅 validator online docs了解更多信息。一旦 Validator 支持 Java 8,它还将支持 Java 8 参数命名工具。

IMO,你应该试试 ParaNamer。

关于java - 我可以更改方法参数的 ConstraintValidator 中的属性路径吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22496527/

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