New @RequestParam annotations in Spring Boot 1.4 (Spring Framework 4.3)

Earlier in Spring/Spring Boot to Map a GET or POST or DELETE or any HTTP method request handler we would write something like below:

@RestController
@RequestMapping("/api/books")
public class BookAPIController {
  @RequestMapping
  public ResponseEntity<?> getBooks(){
  
  }
  
  @RequestMapping("/{book_id}")
  public ResponseEntity<?> getBook(@PathVariable("book_id") String bookId){
  
  }
  
  @RequestMapping(method = RequestMethod.POST)
  public ResponseEntity<?> addNewBook(@RequestBody Map<String, Object> requestBody){
	
  }
  
  @RequestMapping(method = RequestMethod.POST, value="/{book_id}")
  public ResponseEntity<?> editBook(@PathVariable("book_id") String bookId){
	
  }
  
  @RequestMapping(method = RequestMethod.DELETE, value="/{book_id}")
  public ResponseEntity<?> deleteBook(@PathVariable("book_id") String bookId){
	
  }
}

But with Springframework 4.3 and Spring Boot 1.4 (which now uses Springframework 4.3) we have some new annotations to map the HTTP methods to request handlers for the following HTTP methods: GET, POST, PUT, PATCH, DELETE. These new annotations are namely: @GetMapping, @PostMapping, @PutMapping, @PatchMapping, @DeleteMapping. So the above code now looks like:

@RestController
@RequestMapping("/api/books")
public class BookAPIController {
  @GetMapping
  public ResponseEntity<?> getBooks(){}
  
  @GetMapping("/{book_id}")
  public ResponseEntity<?> getBook(
    @PathVariable("book_id") String bookId
  ){}
  
  @PostMapping
  public ResponseEntity<?> addNewBook(
    @RequestBody Map<String, Object> requestBody
  ){}
  
  @PostMapping("/{book_id}")
  public ResponseEntity<?> editBook(
    @PathVariable("book_id") String bookId
  ){}
  
  @DeleteMapping("/{book_id}")
  public ResponseEntity<?> deleteBook(
   @PathVariable("book_id") String bookId
  ){}
}

These new annotations aid in improving the code readability and also reducing the annotation text to some extent

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s