Monday 7 December 2015

Difference between spring @Controller and @RestController annotation

Spring 4.0 doesn’t change a lot when it comes to the MVC framework, it is more focused on Java 8 and JEE 7 compatibility and lot of internal upgrades. One new thing introduced in 4.0 was a new annotation 


  • @Controller is used to mark classes as Spring MVC Controller.

  • @RestController is a convenience annotation that does nothing more than adding  the @Controller and @ResponseBody annotations 


@RestController is composition of @Controller and @ResponseBody, if we are not using the 

@ResponseBody in Method signature then we need to use the @Restcontroller.




@RestController  Example code :-


public class Message {
    String name;
    String text;
    public Message(String name, String text) {
        this.name = name;
        this.text = text;
    }
    public String getName() {
        return name;
    }
    public String getText() {
        return text;
    }
}


import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.websystique.springmvc.domain.Message;
@RestController
public class HelloWorldRestController {
    @RequestMapping("/hello/{hero}")
    public Message message(@PathVariable String hero) {
        Message msg = new Message(player, "Hello " + hero);
        return msg;
    }
}



@PathVariable indicates that this parameter will be bound to variable in URI template. 
More interesting thing to note here is that here we are using @RestController annotation, 
which marks this class as a controller where every method returns a domain object/pojo 
instead of a view. It means that we are no more using view-resolvers, we are no more directly sending the html in response but we are sending domain object converted into format understood by the consumers.

 In our case, due to jackson library included in class path, the Message object will be converted into JSON format.


http://websystique.com/springmvc/spring-4-mvc-rest-service-example-using-restcontroller/





No comments:

Post a Comment