Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
318 views
in Technique[技术] by (71.8m points)

java - How to avoid redundancy when using JSON Schema and Bean Validation annotations?

Is there a good way to use JSON @Schema annotations as well as Java Bean Validations (e.g. hibernate) for validation on client and server side without introducing redundant information with the corresponding annotations?

Assume a Server side code that has some properties (e.g. number of players) which are described by @Schema Annotations. A Front End Client uses those @Schema Annotations to come up with a GUI that allows the user to configure that properties as well as to validate the users input for such properties before even sending the information back to the server. For example:

@Schema(
        title = "number of players",
        description = "property to be specified by User",
        type = "integer",
        minimum = "1",
        multipleOf = 3,
        defaultValue = "3"
)
private int players = 3;

This example already has some unfavorable redundancy as it is defining a defaultValue at two places. One time in the (Java) code itself and another time in the JSON Schema. Putting that aside for now (while clean suggestions are still welcome), I wonder how to avoid even more undesirable redundancy when adding Bean Validations with e.g. Hibernate Validator.

If I would like to add Bean Validations to validate on the server side of things, the code might look like this:

@Schema(
        title = "number of players",
        description = "property to be specified by User",
        type = "integer",
        minimum = "1",
        multipleOf = 3,
        defaultValue = "3"
)
@Min(1)
@NotEmpty
private int players = 3;

More complex validations with custom validation annotations are possible but for the basic problem I lack to grasp this should be enough to understand my difficulties.

What would be an appropriate way to avoid the redundancy of declaring validation constraints such as minimum multiple times (JSON @Schema annotation & @Min Annotation from Hibernate)? I appreciate suggestions and remarks. Thx.

question from:https://stackoverflow.com/questions/65936286/how-to-avoid-redundancy-when-using-json-schema-and-bean-validation-annotations

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...