Reputation: 444
I have an entity XYZ.java
@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 interface XYZCRUD.java
to do CRUD operations on XYZ.java
@Validated
public interface XYZCRUD {
public int insert(@Valid XYZ entity) throws SomeException;
Although javax's @Valid works for @NotNull validation but it does not support passing validation group as annotation attribute from the method from where i am triggering the validation . So I tried using @Validated annotation which does allow to pass groups via an attribute "value" like this
@Validated
public interface XYZCRUD {
public int insert(@Validated(value=SomeGroup.class) XYZ entity) throws SomeException;
However it does not trigger the validation at all.I tried after removing the groups attribute from the field and also from the trigger annotation.
Conclusion : @Validated does not trigger @NotNull
Questions :
NOTE : I am also using lombok if it has something to do with this.
Upvotes: 5
Views: 17682
Reputation: 1685
For @NotNull, you'll need to add the defgault group:
@Validated({ Default.class, Group1.class })
public myMethod1(@NotNull @Valid Foo foo) { ... }
Upvotes: 0
Reputation: 1290
@mayank-vats If you want to apply a group to 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) { ... }
...
}
Upvotes: 4
Reputation: 444
It seems like @Validated was doing its job which is only to mark "parameters" with groups but how is that interpreted ("intercepted") by validation framework is a different story . In my case this is what was happening when method level validation were being intercerpted and validated
From the docs of Spring's MethodValidationInterceptor
Validation groups can be specified through Spring's Validated annotation at the type level of the containing target class, applying to all public service methods of that class. By default, JSR-303 will validate against its default group only.
Which means the ONLY groups mentioned at class level will be validated 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 implementation but this is what the docs say .If someone knows the reason please comment.
Upvotes: 2