Please consider this example:
@ApiModelProperty(required = false, value = "Required only for Ipsum group")
@NotNull(groups = Ipsum.class)
private int lorem;
In this case we have @NotNull annotation, but with specified validation group. Because of that in swagger this property shouldn't be marked as required so we add required=false in @ApiModelProperty. Unfortunately @NotNull annotation seems to have priority over Swagger own @ApiModelProperty and lorem is still marked as required.
This has cost me a major headache too.
I could use this weekness https://github.com/swagger-api/swagger-core/issues/1705#issuecomment-220629231 to achieve a workaround, that works for me.
Create an own NotNull (PartialNotNull) annotation.
Your custom annotation now can use the NotNull annotation inside to get the validation right.
This way Swagger don't recognise your custom annotation to be a NotNull validation annotation and generats the property as not required.
Use it like this
@PartialNotNull(groups = Ipsum.class)
private int lorem;
This is the custom annotation:
@NotNull
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = { })
public @interface PartialNotNull {
String message() default "{javax.validation.constraints.NotNull.message}";
Class>[] groups() default { };
Class extends Payload>[] payload() default { };
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@Documented
@interface List {
PartialNotNull[] value();
}
}
It's kind of hard to support every case with this. To most people, @NotNull means "cannot be null" and "value is required". Thus that annotation is winning. There's no way to handle conflicting configurations without making someone unhappy.
I can see a case where the @ApiModelProperty will _win_ no matter what. Maybe that's the answer but still someone won't like it.
Well, it's weird that external (@NotNull) annotation has priority over library's own annotation (@ApiModelProperty) when it comes to displaying library-specific stuff...
Feel free to send a PR
This is a reasonable request, because we want the api model itself to be reusable when dealing with different type of input situation. I think a feasible solution could be something like notNullGroups inside ApiModelProperty, but again, that would be waste since the NotNull validator has already declared the group.
Most helpful comment
Well, it's weird that external (
@NotNull) annotation has priority over library's own annotation (@ApiModelProperty) when it comes to displaying library-specific stuff...