We will start with new improvements in Spring Boot 1.4 and Spring Framework 4.3 and explain the improvements with an example.
There are some new improvements in Spring Boot 1.4 and Spring 4.3 which lead to a better readability and some use of annotations, particularly with HTTP request methods.
We usually map GET, PUT, POST and DELETE HTTP method in rest controller in the following way.
@RestController
@RequestMapping("/api/employees")
public class EmployeeController {
@RequestMapping
public ResponseEntity<List<Employee>> getAll() {
return ResponseEntity.ok(Collections.emptyList());
}
@RequestMapping("/{employeeId}")
public ResponseEntity<Employee> findById(@PathVariable Long employeeId) {
return ResponseEntity.ok(EmployeeStub.findById(employeeId));
}
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<Employee> addEmployee(@RequestBody Employee employee) {
return ResponseEntity.ok(EmployeeStub.addEmployee(employee));
}
@RequestMapping(method = RequestMethod.PUT)
public ResponseEntity<Employee> updateEmployee(@RequestBody Employee employee) {
return ResponseEntity.ok(EmployeeStub.updateEmployee(employee));
}
@RequestMapping(path = "/{employeeId}", method = RequestMethod.DELETE)
public ResponseEntity<Employee> deleteEmployee(@PathVariable Long employeeId) {
return ResponseEntity.ok(EmployeeStub.deleteEmployee(employeeId));
}
}
But with Spring Framework 4.3 and Spring Boot 1.4, we have new annotations to map the HTTP methods.
/**
*
* @author Gaurav Rai Mazra
*
*/
@RestController
@RequestMapping("/api/employees")
public class EmployeeController {
@GetMapping
public ResponseEntity<List<Employee>> getAll() {
return ResponseEntity.ok(Collections.emptyList());
}
@GetMapping("/{employeeId}")
public ResponseEntity<Employee> findById(@PathVariable Long employeeId) {
return ResponseEntity.ok(EmployeeStub.findById(employeeId));
}
@PostMapping
public ResponseEntity<Employee> addEmployee(@RequestBody Employee employee) {
return ResponseEntity.ok(EmployeeStub.addEmployee(employee));
}
@PutMapping
public ResponseEntity<Employee> updateEmployee(@RequestBody Employee employee) {
return ResponseEntity.ok(EmployeeStub.updateEmployee(employee));
}
@DeleteMapping(path = "/{employeeId}")
public ResponseEntity<Employee> deleteEmployee(@PathVariable Long employeeId) {
return ResponseEntity.ok(EmployeeStub.deleteEmployee(employeeId));
}
}
These annotations has improved the readability of the code. I hope you find this post helpful. You can get full example code on Github.