Top 10 Spring MVC and REST Annotations with Examples for Java Programmers

Hello guys, welcome to my third article on exploring essential annotations from the Spring framework, the most popular framework for Java development. In the first article, I have shared some of the most useful Spring Framework annotations, which were based upon Core Spring functionalities like dependency injection, inversion of control, and configuration, and in the second article, we have learned about important Spring Cloud annotations like @EnableConfigServer, @EnableEurekaSever, and @EnableDiscoveryClient. Now that you know those essential Spring annotations it's time to move towards Spring MVC and REST, one of the most used parts of Spring Framework.

In this article, you will learn some of the essential Spring MVC and REST annotations like @Controller, @RequestMapping, and @RestController. These annotations are very useful for creating Spring-based Java web application and RESTful web services.

I particularly like Spring MVC's support for developing RESTful web services in Java. As I have explained in my earlier article 7 reasons to use Spring MVC for REST in Java, it provides convenient annotations like @RestController, @ResponseBody, and @ResponseStatus to create fully functional REST APIs in Java.

In addition to exploring core Spring MVC annotations like @RequestMapping, @RequestParam, and @PathVariable, we'll also explore those which are immensely helpful for developing REST APIs in Java.

Btw, if you have worked in Spring MVC then you should already have some basic ideas about these annotations, but if you don't have any prior experience and just started with Spring framework and Spring MVC then I suggest you to first go through a comprehensive course like Spring Framework 5: Beginner to Guru course on Udemy.  One of the most useful courses on Spring framework.





10 Spring MVC and REST annotations for Java developers

Without wasting any more of your time, here is my list of some of the must-know Spring MVC and REST annotations for Java developers. If you have used Spring MVC to create a web application or RESTful applications then you should already be familiar with these but if you haven't don't worry, you'll learn in this article.

Top 10 Spring MVC and REST Annotations Java Developer Should Know


Btw, I'll not go in too much detail about covering every single option and functionality of these annotations, just to keep this article in reasonable length, but will give you resources like Spring in Action book where you can learn these annotations and their use in depth.


1. @Controller

This annotation is used to make a class as web controller, which can handle client requests and send a response back to the client. This is a class level annotation, which is put on top of your controller class. Similar to @Service and @Repository it is also a stereotype annotation. If you are wondering what is the difference between them then you can also see this article to learn more about their differences.

Here is an example of @Controller annotation in Spring MVC:

@Controller
public class HelloController{
// handler methods
}

This is a simple controller class which contains handler methods to handle HTTP request for different URLs. You don't need to extend a class or implement an interface to create the controller anymore.



2. @RequestMapping

The Controller class contains several handler methods to handle different HTTP request but how does Spring map a particular request to a particular handler method? Well, that's done with the help of the @RequestMapping annotation. It's a method level annotation which is specified over a handler method.

It provides the mapping between the request path and handler method. It also supports some advanced option which can be used to specify separate handler methods for different types of request on the same URI like you can specify a method to handle GET request and another to handle POST request on same URI.

Here is an example of @RequestMapping annotation in Spring MVC:

@Controller
public class HelloControler{

  @RequestMapping("/")
  public String hello(){
    return "Hello Spring MVC";
  }
}

In this example, the home page will map to this handler method. So any request comes to the localhost:8080 will go to this method which will return "Hello Spring MVC".

The value attribute of @RequestMapping annotation is used to specify the URL pattern but if there are no more arguments then you also omit that.

You can also specify the HTTP method using RequestMethod attribute. If you are new to Spring MVC, I suggest you go through  Introduction to Spring MVC by Bryan Hansen on Pluralsight to learn more about how to handle only GET or POST requests on a particular URL.





3. @RequestParam

This is another useful Spring MVC annotation which is used to bind HTTP parameters into method arguments of handler methods. For example, if you send query parameters along with URLlikie for paging or just to supply some key data then you can get them as method arguments in your handler methods.

Here is an example of @RequestParam annotation in Spring MVC from my earlier article about the difference between RequestParam and PathVariable annotation:

@RequestMapping("/book")
public String showBookDetails(

@RequestParam("ISBN") String ISBN, Model model){
  model.addAttribute("ISBN", ISBN);
  return "bookDetails";
}

If you access your web application which provides book details with a query parameter like below:

http://localhost:8080/book?ISBN=900848893

then above handler method will be called because it is bound to the "/book" URL and the query parameter ISBN will be used to populate the method argument with the same name "ISBN" inside showBookDetails() method.

You can even use a different name of your choice. If you are interested in learning more about @RequestParam annotation and its various options then Spring MVC For Beginners: Build Java Web App in 25 Steps on Udemy is a great place to start with.

Useful Spring MVC and REST Annotations Java Developer



4. @PathVariable

This is another annotation which is used to retrieve data from the URL. Unlike @RequestParam annotation which is used to extract query parameters, this annotation enables the controller to handle a request for parameterized URLs like URLs that have variable input as part of their path like:

http://localhost:8080/books/900083838

If you want to retrieve the ISBN number "900083838" from the URL as method argument then you can use @PathVariable annotation in Spring MVC as shown below:

@RequestMapping(value="/books/{ISBN}",
                        method= RequestMethod.GET)
public String showBookDetails(@PathVariable("ISBN") String id,
Model model){
   model.addAttribute("ISBN", id);
   return "bookDetails";
}

The Path variable is represented inside curly braces like {ISBN}, which means the part after /books is extracted and populated on method argument id, which is annotated with @PathVaraible.

In short, this annotation binds placeholder from the URI to a method parameter inside the handler method. This is immensely useful while developing RESTful web services which contains useful data as part of their URL.



5. @RequestBody

This annotation can convert inbound HTTP data into Java objects passed into the controller's handler method. Just as @ResponseBody tells the Spring MVC to use a message converter when sending a response to the client, the @RequestBody annotations tell the Spring to find a suitable message converter to convert a resource representation coming from a client into an object.

Here is an example:

@RequestMapping(method=RequestMethod.POST, consumers= "application/json")
public @ResponseBody Course saveCourse(@RequestBody Course aCourse){
   return courseRepository.save(aCourse);
}

This is again a very useful annotation while developing RESTful web service in Java using Spring framework and one of the reasons why I love to write RESTful API using Spring.

If you are also interested in developing RESTful application in Java then I suggest going through Eugen Parachiv's REST with Spring Certification class on Baeldung. He has shared his years of experience in developing REST-based applications using Spring in this course.




6. @ResponseBody

The @ResponseBody annotation is one of the most useful annotations for developing RESTful web service using Spring MVC. This annotation is used to transform a Java object returned from he a controller to a resource representation requested by a REST client. It can completely bypass the view resolution part.

Here is an example of @ResponseBody annotation in Spring MVC:

@RequestMapping(method=RequestMethod.POST,consumers= "application/json")
public @ResponseBody Course saveCourse(@RequestBody Course aCourse){
  return courseRepository.save(aCourse);
}

This is the same as the previous example but the @ResponseBody is used to indicate that the response returned by this method will be converted into a resource which the client can consume.

If you have created any RESTful web service with Spring MVC then you know that we need to annotate each method which generates REST response with the @ResponseBody annotation but with the introduction of @RestController, we can avoid this.




7. @RestController

This is convenience annotation for developing RESTful web service with Spring MVC framework. The @RestController is a combination of @Controller and @ResponseBody, which was introduced in the Spring 3.4 version.

When you annotate a controller class with @RestController it does two purposes, first, it says that the controller class is handling a request for REST APIs and second you don't need to annotate each method with the @ResposneBody annotation to signal that the response will be converted into a Resource using various HttpMessageConverers.

Here is an example of @RestController annotation in Spring MVC:

@RestController
class HelloControler{

@RequestMapping("/")
public String hello(){
  return "Hello Spring Booot";
}

}

You can see that there is no @ReseponseBody annotation is required to generate RESTful response. Before @RestController, Java developer used @Controller on top of the class and annotated each handler method with @ResponseBody annotation.

Spring designer saw this and make life easier by introducing @RestController. If you are interested, you can learn more about it on RESTful Web Services with Java and Spring, a comprehensive course for developing a real world and secure REST API with Java and Spring.
You will also learn about Implementing API calls, Sign-up, sign-in, email verification, password reset, update, delete and even how to deploy RESTFul Java apps on Amazon AWS Cloud.

Spring MVC Annotations with Examples



8. @SprinbBootApplication

This is a relatively new annotation but very useful if you are using Spring Boot for creating Java web application with Spring. This single annotation combines three annotations like @Configuration, @EnableAutoConfiguration, and @ComponentScan. If you use Spring Boot, then you can run your application without deploying into a web server, as it comes with an embedded Tomcat server.

When you annotated your Main class with @SpringBootApplication then it enables Java-based configuration as well as component scanning and auto-configuration feature of Spring Boot, which can magically set up things for you by just dropping the required JAR into classpath.

here is an example of using @SpringBootApplicaiton annotation in Spring:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication 
// same as @Configuration @EnableAutoConfiguration @ComponentScan
public class SpringBootApp{

 public static void main(String[] args) {
  SpringApplication.run(SpringBootApp.class, args);
 }

}

Since Spring Boot provides many features to make Java development with Spring easier, I suggest you to use Spring Boot going forward. If you are new to Spring boot then Spring Boot MasterClass course on Udemy is one of the valuable resources to learn and master Spring Boot.



9. @EnableAutoConfiguration

This is another Spring boot annotation which enables the auto-configuration feature, which makes Spring guess the configuration based on the JAR presents in the classpath.

This is actually the original annotation which was used to enable/disable auto-configuration, present from the very first release of Spring Boot. Since it was constantly used with @Configuration and @ComponentScan on an earlier version of Spring boot, they have come up with a convenience @SpringBootApplication annotation.

Though you can still use @EnableAutoConfiguration annotation if you want to customize or have some control over auto-configuration.

For example, you can exclude certain classes from auto-configuration as shown in the following example from my earlier post about the difference between @SpringBootApplication and @EnableAutoConfiguration in Spring boot:

@Configuration
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class MyConfiguration {
  //.. Java code
}

If you want to learn more about this annotation then Spring Boot in Action by Craig Walls is one of the best resources to start with.



10. @ResponseStatus

This annotation can be used to override the HTTP response code for a response. You can use this annotation for error handling while developing a web application or RESTful web service using Spring. Here is an example of @ResponseStatus inspired by my favorite Spring in Action book:

@Exceptionhandler(BookNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public Error bookNotFound(BookNotFoundException bnfe){
  long ISBN = bnfe.getISBN();
  return new Error(4, "Book [" + ISBN + "] not found");
}

Here we are returning an error if the book for given ISBN is not found in our library and we have used @ResponseStatus to override the HTTP status code as 404 to indicate client a missing resource.


That's all about some of the essential Spring MVC and REST annotations. As a Java developer, you should be familiar with these annotations, especially if you are using Spring MVC for creating a web application or RESTful web service in Java. If you want to learn more about these annotations and various options to configure and use them, here are some resources you can consult.

Further Learning
Master Microservices with Spring Boot and Spring Cloud
Top 5Spring and Hibernate Trainign courses
5 Free Spring Framework and Spring Boot Courses
15 Spring Boot Interview Questions with Answers
Top 10 Spring Framework Interview Questions
20 REST with Spring Interview Questions for Web developers
3 ways to learn Core Spring or Spring MVC better
6 Courses to learn Spring Framework in Depth
30+ Spring MVC Interview Questions for Java Developers
How to crack Spring Core Professional 5.0 Certification

Thanks for reading this article so far. If you find these Spring MVC annotations useful then please share with your friends and colleagues on Facebook and Twitter. If you have any questions or feedback then please drop a note.

No comments:

Post a Comment