Mayank Kumar Thakur
Mayank Kumar Thakur

Reputation: 704

Ways to create object of ResponseEntity class in spring boot

I am new to spring boot and I am trying to create handler methods to create REST API in spring boot. To handle request localhost:8080/stack I created below handler method in which I used constructor of ResponseEntity to create its object and pass it in return statement.

 @GetMapping("/stack")
    public ResponseEntity<String> stack(){
        System.out.println("I am stack method");
        return new ResponseEntity<>("Body",HttpStatus.OK);
    }
}

But I can also do it by using the below method

 @GetMapping("/stack")
    public ResponseEntity<String> stack(){
        System.out.println("I am stack method");
        return ResponseEntity.status(HttpStatus.OK).body("Body");
    }

I don't know which is the best way to create and return an object of ResponseEntity in the handler method using constructors or using build method() and why? Somebody please help here. Which is the most preferred way in the production?

Upvotes: 0

Views: 15250

Answers (3)

Abhinav
Abhinav

Reputation: 540

It's the same as even 2nd approach returns a new object of ResponseEntity class. If you check the implementation of the body method as below:-

@Override
    public <T> ResponseEntity<T> body(@Nullable T body) {
        return new ResponseEntity<>(body, this.headers, this.statusCode);
    }

Upvotes: 2

Krzysztof K
Krzysztof K

Reputation: 784

In that case best way is to return string ("Body") from restcontroller method, it'll be wrapped in responseentity with response status 200 OK automatically

Upvotes: 0

sanjeevRm
sanjeevRm

Reputation: 1606

ResponseEntity is meant to represent the entire HTTP response. You can control anything that goes into it: status code, headers, and body.

@ResponseBody is a marker for the HTTP response body and @ResponseStatus declares the status code of the HTTP response.

@ResponseStatus isn't very flexible, ResponseEntity lets you do more.

Upvotes: 0

Related Questions