Java 如何使用hibernate验证器为验证传递不同的错误代码?

Java 如何使用hibernate验证器为验证传递不同的错误代码?,java,spring,spring-boot,validation,hibernate-validator,Java,Spring,Spring Boot,Validation,Hibernate Validator,我正在使用hibernate验证器在我的应用程序中实现验证。我还为业务验证需求使用了自定义注释和自定义验证器。它工作正常,我能够根据实现获得具体的错误消息。但是,现在我还想将每个验证的错误代码(类似于下面代码片段中给出的代码)以及错误消息返回给调用validate方法的方法 我已经阅读了hibernate验证的文档,但是找不到与此需求相关的任何内容。有人能帮我实现这个场景中的错误代码吗 @ValidStateInCountry(code=006, message="Invalid st

我正在使用hibernate验证器在我的应用程序中实现验证。我还为业务验证需求使用了自定义注释和自定义验证器。它工作正常,我能够根据实现获得具体的错误消息。但是,现在我还想将每个验证的错误代码(类似于下面代码片段中给出的代码)以及错误消息返回给调用validate方法的方法

我已经阅读了hibernate验证的文档,但是找不到与此需求相关的任何内容。有人能帮我实现这个场景中的错误代码吗

@ValidStateInCountry(code=006, message="Invalid state for given country")
@ValidZipInCountry(code=007, message="Invalid zip for given country")
public class  Address {

@NotBlank(code=001, message="address line is mandatory")
private String addressLine;

@ValidCountry(code=002, message="Invalid Country name")
@NotBlank(code=003, message="Country name is mandatory")
private String country;

@NotBlank(code=004, message="state is mandatory")
private String state;

@NotBlank(code=005, message="zip is mandatory")
private String zipCode;

}

首先,对于内置约束,我们不支持这样做,因此您必须自己重新实现它们才能添加此功能

其次,我认为您需要的是我们所称的动态有效负载,您可以在
约束验证器中创建它时将其附加到
约束violation
。然后,您可以将违规行为分解为特定于Hibernate验证器的风格,并利用它。有关完整示例,请参见


通过实现
initialize()
::。

一个好问题,您可以从注释中提取一次错误代码。你试过这种方法吗?:@J Woodchuck:是的,我试过了,但在我的情况下不起作用。我有多个类级和属性级自定义验证器,每次验证失败都需要单独的错误代码。