How to test method argument using @Validated group-based annotations

I have an XYZ.java object

 @Getter @Setter @NoArgsConstructor @AllArgsConstructor @ToString public class XYZ extends BaseEntity implements Serializable { @NotNull (groups = {Groups.Insert.class, Groups.Delete.class, Groups.Update.class, Groups.Select.class}) private String X; 

and there is an XYZCRUD.java interface for performing CRUD operations on XYZ.java

 @Validated public interface XYZCRUD { public int insert(@Valid XYZ entity) throws SomeException; 

Although javax @Valid works for @NotNull validation, it does not support passing the validation group as an annotation attribute from the method from which I run validation. So I tried using the @Validated annotation, which allows you to pass groups through a value attribute like this

 @Validated public interface XYZCRUD { public int insert(@Validated(value=SomeGroup.class) XYZ entity) throws SomeException; 

However, it does not call a check at all. I tried to remove the group attribute from the field as well as from the trigger annotation.

Conclusion: @Validated does not call @NotNull

Questions:

  • Why doesn't @Validated call javax @NotNull? Am I doing something wrong or not supporting it?
  • Is there any other way? cannot implement custom validator

NOTE. I also use lombok if it has anything to do with this.

+4
source share
4 answers

It seems that @Validated was doing its job, which should only mark “parameters” in groups, but how it is interpreted (“intercepted”) using a validation framework is a different story. In my case, this is what happened when the method level check was nested and checked

From Spring Docs MethodValidationInterceptor

Validation groups can be specified using Spring Validated annotation at the level of the type containing the target class, applicable to all public service methods for this class. By default, JSR-303 will only check its default group.

This means that the groups ONLY mentioned at the class level will be checked, and they will be used for all public methods .

 @Validated(value=SomeGroup.class)//this will be used as group for all methods being validated public interface XYZCRUD { public int insert(@Valid XYZ entity) throws SomeException; public int delete(@Valid XYZ entity) throws SomeException; 

I do not understand the reason for such an implementation, but this is what the documents say. If someone knows the reason, please comment.

+2
source

@ mayank-vats If you want to apply a group to a specific method (not all public methods), you can use:

 @Validated public class MyClass { @Validated({Group1.class}) public myMethod1(@Valid Foo foo) { ... } @Validated({Group2.class}) public myMethod2(@Valid Foo foo) { ... } ... } 
+1
source
0
source

For @NotNull you need to add a defgault group:

 @Validated({ Default.class, Group1.class }) public myMethod1(@NotNull @Valid Foo foo) { ... } 
0
source

All Articles