ResponseEntity return type wildcard with swagger generated interface

Viewed 694

I want to know the difference between returning ResponseEntity<?> with wildcard VS ResponseEntity<ABC.class> as return type when Swagger generated API interface contains 2 different classes as return types, i.e one for an exception and another for normal flow.

My controller interface is :-

   @Operation(summary = "Get user by user name", tags = { "user" })
   @ApiResponses(value = {
       @ApiResponse(responseCode = "200", description = "successful operation", content = @Content(schema = @Schema(implementation = User.class))),
       @ApiResponse(responseCode = "400", description = "Invalid username supplied", content = @Content(schema = @Schema(implementation = Error.class)))
   })
   @GetMapping(value = "/user/{username}", produces = { "application/xml", "application/json" })
   ResponseEntity<?> getUserByName(@PathVariable("username") String username);

the @Schema defines return type.

Can I use ResponseEntity<User> instead of the <?> for the getUserByName method ?

I have the the global exception handler @ControllerAdvice in my application which returns ResponseEntity<Error> .

1 Answers

Answer for your question is simply Yes. Since you are using a Controller Adviser, you can directly define the endpoint return type as User in ResponseEntity

Using a Wildcard(ResponseEntity<?>) as a return type, the symbol ? defines that the return value of the controller method can be any type of ResponseEntity.

Using as ResponseEntity<?> or simply keep it as ResponseEntity<> are considered as raw type of its usage.

But really it is not a good practice to do so. So, you have to declare the exact return type of the controller method in this format ResponseEntity<ABC>.

Let's take this example java of method returning a list of objects(List<Object>).

Is it possible on this list to add a Car.class type, a Van.class type. But how ever the consumer of a method should not have to deal with such disruptive questions and we have to define an exact type.

Yes you can use ResponseEntity<User> if your method returns a User type ResponseEntity.

I hope this'll help you to solve the issue :)

Related