What's the reason to use ResponseEntity<?> return type instead of simple ResponseEntity in Spring Controller?

Viewed 6000

I've seen a lot of examples of Spring Controllers implementation that use ResponseEntity<?> in order to return HTTP response that have a specific status code and optional body.

ResponseEntity<?> notation is present even in official Spring tutorials like the following one: Building REST services with Spring

What's the reason to use ResponseEntity<?> instead of simple ResponseEntity?

It's a little bit related to my previous question: SonarQube complains about using ResponseEntity with a wildcard

There is some explanation in What is a raw type and why shouldn't we use it? thread, but I'd like to pay more attention to ResponseEntity class and it's use in Spring Controllers.

Consider the following snippet of code where somethingService returns an Optional of Something class:

@GetMapping
ResponseEntity<?> getSomething() {
    return somethingService.getSomething()
               .map(smth -> new ResponseEntity<>(smth, HttpStatus.OK))        
               .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
}

Is there any reason to leave a wildcard even if I don't get any profit from compiler checks since ResponseEntity(HttpStatus status) parametrises ResponseEntity with Object class?

0 Answers
Related