Home >Java >How to access instance variables when inserting messages in Hibernate Validator?

How to access instance variables when inserting messages in Hibernate Validator?

WBOY
WBOYforward
2024-02-14 13:42:09749browse

In Hibernate Validator, we often need to customize validation messages. Sometimes, we need to access instance variables to generate messages dynamically. So, how to access instance variables in Hibernate Validator? First, we need to use placeholders in the validation annotation to reference the instance variables. Then, in the message resource file, we can use "{}" to get the value of the instance variable. This way we can flexibly insert the values ​​of instance variables to generate personalized validation messages. In this article, PHP editor Yuzai will introduce you in detail how to access instance variables when inserting messages in Hibernate Validator.

Question content

I am using hibernate validator and spring to validate the object when inserting it into the repository using crudrepository::save. Suppose we have class:

public class Person {
  public int id;

  @NotBlank(message="User with id: ${id} is missing name")
  public String name;

}

I want the interpolated message to be able to access all the fields of the person instance, such as the id field, and then access them like "${id}" or "${this.id}". The documentation mentions something about being able to access all bean properties, but I guess it only works with class level constraints.

Is there some way to do this without resorting to class-level constraints?

Workaround

Constraint validators cannot access any information outside the field itself. So, in other words, there is no way to access sibling fields. This has to do with the scope of the constraint. Look at it this way:

@NotBlank
public String name;

Non-empty name can be a personal field, or a field in a company or other class. It is indistinguishable from where @notblank is.

So, as you suggested in your question, in order to access other class fields when inserting messages, the constraints should be at class level... To avoid creating tons of custom constraints, you might consider looking at @scriptassert.

Also note that constraintviolationexception contains the constraintviolation list from which you should be able to access the leaf bean (getleafbean()) or the root bean (getrootbean ()) and get the information you need after throwing the exception.

The above is the detailed content of How to access instance variables when inserting messages in Hibernate Validator?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete