Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@NotNull annotation not working as expected Java Jersey

Tags:

java

rest

http

api

I have an endpoint implementation, that I am passing an object to in the parameter list. I am trying to verify that this object is not null, using the @NotNull annotation.

@POST 
@Path("path") 
public Response endpointMethod(@NotNull @ApiParam(value = "abc", required = true) Object object) { 
        return Response.status(Status.OK).build(); 
} 

If the object is verified to be not null, then the endpoint will just return a 200 OK response. However, when I fire a request to this endpoint, with the specified path, and nothing in the body, there are no errors that are thrown. Instead, I am able to retrieve the 200 response (even when I check if the object is null before return the response, it shows that that is the case).

Can someone guide me on how to verify whether the object is null in the correct way?

like image 442
Adam Avatar asked Mar 07 '16 21:03

Adam


People also ask

What is @NotNull annotation in Java?

The @NotNull annotation is, actually, an explicit contract declaring that: A method should not return null. Variables (fields, local variables, and parameters) cannot hold a null value.

What exception does @NotNull throw?

NullPointerException will be thrown with 'field name is marked non-null but is null' as the exception message.

What does @NotNull annotation mean in bean property?

@NotNull validates that the annotated property value is not null. @AssertTrue validates that the annotated property value is true. @Size validates that the annotated property value has a size between the attributes min and max; can be applied to String, Collection, Map, and array properties.

What is the difference between @NotNull and @NotBlank?

3. @NotNull – Checks that the annotated value is not null. 4. @NotBlank – Checks that the annotated character sequence/string is not null and the trimmed length is greater than 0.


1 Answers

If you have bean-validation dependency on classpath (org.glassfish.jersey.ext:jersey-bean-validation:2.22.2) it should be picked up by the framework and work out of the box.

Also make sure that your @NotNull annotation comes from javax.validation.constraints package

like image 142
Łukasz Avatar answered Oct 02 '22 22:10

Łukasz