@RestController and @Controller annotation example in Spring Boot

Here we will see @RestController and @Controller annotation example in Spring Boot.

Basic points about @RestController and @Controller annotation.

@RestController annotation.

  • This annotation introduced in Spring  4.0, available in org.springframework.web.bind.annotation package.
  • It has one optional element i.e value.
  • We use this annotation with the class.
  • This annotation is a combined form of @Controller and @ResponseBody
  • Internal implementation –

 

 @Controller annotation.

  • This annotation introduced in Spring 2.5, available in org.springframework.stereotype package.
  • It has one optional element i.e value.
  • We use this annotation with the class, in case of this annotation we need to use @ResponseBody explicitly.
  • Internal implementation –

 

Note –  What will happen if we use @RestController with the method or interface? With the method, it will give compilation error but if we use this annotation with an interface no compilation error. If we use @RestController with the interface then we need to provide corresponding implementation classes.

 

 

@RestController annotation example.

prerequisites –

  • JDK 1.8
  • Eclipse
  • maven
  • postman

Create maven project, Don’t forget to check ‘Create a simple project (skip)’click on next. Fill all details(GroupId – restcontrollerexample, ArtifactId – restcontrollerexample and name – restcontrollerexample) and click on finish. Keep packaging as the jar.

Make sure we have a correct pom.xml.

 

Define Contoller(RestControllerExampleEndPoint.java), SpringBootMain(SpringRestControllerExample.java), and Entity class(Book.java).

RestControllerExampleEndPoint.java

 

SpringRestControllerExample.java

Book.java

 

If you encounter any port related issue, define application.properties and change the port.

application.properties

server.port = 9093

 

Run the main class(SpringRestControllerExample.java).

 

 

Call rest URI(http://localhost:9093/simpleuri) from postman

 

@RestController and @Controller annotation example in Spring Boot

 

 

@Controller annotation example.

Let’s modify the controller class, we will not use @Responsebody annotation and see what happens.

 

Run the main class and hit the rest URI from the postman.

 

 

Let’s use @ResponseBody with method or class.

Again run the main class.

 

 

Yes, we have a response now.

That’s all about @RestController and @Controller annotation example in Spring Boot.

You may like.

 

Top