您可以尝试使用-parameters
或指示您的 IDE 编译您的应用程序,例如在 eclipse 的情况下:首选项 - > java - > 编译器 - >“存储有关方法参数的信息(可通过反射使用)”
有了它,您就需要指示 Bean Validation 基础设施(例如)hibernate-validator 使用ReflectiveParameterNamer
via META-INF/validation.xml
。
<parameter-name-provider>org.hibernate.validator.parameternameprovider.ReflectionParameterNameProvider</parameter-name-provider>
另请参阅Hibernate 验证器配置
我得到了可靠地使用Paranamer 库的东西
META-INF/validation.xml
:
<?xml version="1.0" encoding="UTF-8"?>
<validation-config
xmlns="http://jboss.org/xml/ns/javax/validation/configuration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://jboss.org/xml/ns/javax/validation/configuration
validation-configuration-1.1.xsd"
version="1.1">
<default-provider>org.hibernate.validator.HibernateValidator
</default-provider>
<message-interpolator>org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator
</message-interpolator>
<traversable-resolver>org.hibernate.validator.internal.engine.resolver.DefaultTraversableResolver
</traversable-resolver>
<constraint-validator-factory>org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorFactoryImpl
</constraint-validator-factory>
<parameter-name-provider>org.hibernate.validator.parameternameprovider.ParanamerParameterNameProvider</parameter-name-provider>
</validation-config>
要paranamer
使用 wildfly,我需要创建一个parameter-namer
jboss-module 并从模块中引用该module.xml
模块hibernate-validator
。
有了这个,我可以简单地写:
@POST
public Response login(@NotNull @Valid @Named("authRequest") AuthRequest authRequest) {
return Response.ok().build();
}
...
public class AuthRequest {
@NotNull(message = AuthMessages.EMAIL_REQUIRED)
public String email;
@NotNull(message = AuthMessages.PASSWORD_REQUIRED)
public String password;
}
对通过发送的请求产生以下响应curl
:
curl -H "Content-Type: application/json" -H "Accept: application/json" -d '{"email":"foo@bar.com"}' -v http://localhost:8080/javaweb-training/resources/auth
回复:
{"exception":null,"fieldViolations":[],"propertyViolations":[],"classViolations":[],"parameterViolations":[{"constraintType":"PARAMETER","path":"login.authRequest.password","message":"password.required","value":""}],"returnValueViolations":[]}%
...注意login.authRequest.password
,而不仅仅是login.arg0.password