Spring @RestController Annotation
April 24, 2020
This page will walk through Spring @RestController
annotation example. The @RestController
is the replacement of @Controller
and @ResponseBody
annotation. We can equate them as following.
@RestController = @Controller + @ResponseBody
Find the
@RestController
annotation definition from Spring doc where we can see that @RestController
itself is annotated with @Controller
and @ResponseBody
.
@Target(value=TYPE) @Retention(value=RUNTIME) @Documented @Controller @ResponseBody public @interface RestController { ------ }
@RestController
is useful for REST web service controller where the methods annotated with @RequestMapping
need @ResponseBody
annotation by default. The @RestController
has been introduced in Spring 4.
@Controller
The
@Controller
is annotated at class level to indicate that the class will serve as web controller. The @Controller
is the specialization of @Component
and hence implementation classes are auto detected through classpath scanning. As @RestController
itself is annotated with @Controller
annotation, so the classes annotated with @RestController
are also auto detected through classpath scanning.
@ResponseBody
The
@ResponseBody
is used to indicate that returned object by the method will be response body. The @ResponseBody
creates a response body as JSON, XML and other media type on the basis of MessageConverter
, media-type configured by produces attribute in @RequestMapping
annotation and media-type configured by accept request header.
Here on this page we will understand using
@RestController
in our REST web service application with complete example.
Contents
1. Using @RestController
The classes annotated with@RestController
use @RequestMapping
, @GetMapping
and other annotations to create controller methods. Find the sample code to create Spring REST web service controller.
@RestController public class BookController { @RequestMapping("books") public List<Book> getBooks() { ------ return list; } }
@ResponseBody
is not required with web service method to generate response. It is because we are using @RestController
annotation.
Now when we access the REST url
http://localhost:8080/books
[ {"bookId":101,"name":"Java Tutorials","writer":"Krishna"}, {"bookId":102,"name":"Spring Tutorials","writer":"Mahesh"} ]
@Controller
and @ResponseBody
annotation.
@Controller public class BookController { @RequestMapping("books") public @ResponseBody List<Book> getBooks() { ------ return list; } }
2. Produce JSON Response
To produce JSON response, use media-type asapplication/json
. Spring provides JSON MessageConverter
by default.
@RestController public class BookController { @GetMapping(value = "booksJson", produces = { MediaType.APPLICATION_JSON_VALUE }) public List<Book> getBooks() { ------ return list; } }
3. Produce XML Response
To produce XML response, use media-type asapplication/xml
.
@RestController public class BookController { @GetMapping(value = "booksXml", produces = { MediaType.APPLICATION_XML_VALUE }) public List<Book> getBooks() { ------ return list; } }
MessageConverter
in our Java configuration files. In Spring Boot application, if jackson-dataformat-xml is available in classpath then our REST web service method will produce XML response automatically. Find the Maven dependency to resolve jackson-dataformat-xml in our application.
<dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-xml</artifactId> <version>2.10.3</version> </dependency>
4. Complete Example
Find the web service code using@RestController
annotation.
pom.xml
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.6.RELEASE</version> <relativePath /> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-xml</artifactId> <version>2.10.3</version> </dependency> </dependencies>
package com.concretepage.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import com.concretepage.domain.Book; import com.concretepage.service.BookService; @RestController public class BookController { @Autowired private BookService bookService; @GetMapping(value = "booksJson", produces = { MediaType.APPLICATION_JSON_VALUE }) public List<Book> getBooksJson() { List<Book> list = bookService.getAllBooks(); return list; } @GetMapping(value = "booksXml/{writer}", produces = { MediaType.APPLICATION_XML_VALUE }) public List<Book> getBooksXml(@PathVariable("writer") String writer) { List<Book> list = bookService.getBooksByWriter(writer); return list; } }
package com.concretepage.domain; public class Book { private int bookId; private String name; private String writer; public Book() {} public Book(int bookId, String name, String writer) { this.bookId = bookId; this.name = name; this.writer = writer; } //Setters and Getters }
package com.concretepage.service; import java.util.Arrays; import java.util.List; import org.springframework.stereotype.Service; import com.concretepage.domain.Book; @Service public class BookService { public List<Book> getAllBooks() { // Perform database operation Book b1 = new Book(101, "Java Tutorials", "Krishna"); Book b2 = new Book(102, "Spring Tutorials", "Mahesh"); Book b3 = new Book(103, "Angular Tutorials", "Krishna"); return Arrays.asList(b1, b2, b3); } public List<Book> getBooksByWriter(String writer) { System.out.println("Books by " + writer); // Perform database operation Book b1 = new Book(101, "Java Tutorials", "Krishna"); Book b3 = new Book(103, "Angular Tutorials", "Krishna"); return Arrays.asList(b1, b3); } }
package com.concretepage; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } }
Find the client code using
RestTemplate
.
RestClientUtil.java
package com.concretepage.client; import java.net.URI; import java.net.URISyntaxException; import org.springframework.web.client.RestTemplate; import com.concretepage.domain.Book; public class RestClientUtil { public void getBooksDemoJson() throws URISyntaxException { URI uri = new URI("http://localhost:8080/booksJson"); RestTemplate restTemplate = new RestTemplate(); Book[] books = restTemplate.getForObject(uri, Book[].class); for (Book b : books) { System.out.println(b); } } public void getBooksDemoXml() { String url = "http://localhost:8080/booksXml/{writer}"; String writer = "Krishna"; RestTemplate restTemplate = new RestTemplate(); Book[] books = restTemplate.getForObject(url, Book[].class, writer); for (Book b : books) { System.out.println(b); } } public static void main(String args[]) throws URISyntaxException { RestClientUtil util = new RestClientUtil(); util.getBooksDemoJson(); util.getBooksDemoXml(); } }
5. Run Application
Download the project and run the following command from root folder of the project using command prompt.mvn spring-boot:run
a. Now run
RestClientUtil
as Java Application and we will get below Output.
101, Java Tutorials, Krishna 102, Spring Tutorials, Mahesh 103, Angular Tutorials, Krishna 101, Java Tutorials, Krishna 103, Angular Tutorials, Krishna
http://localhost:8080/booksJson
c. Access URL
http://localhost:8080/booksXml/Krishna