Introduction
Spring Boot provides a comprehensive set of annotations that simplify the development of microservices. These annotations reduce boilerplate code and enable developers to build robust, scalable microservices with minimal configuration. Understanding these annotations is crucial for building production-ready microservices applications.
This guide covers the essential annotations used in Spring Boot microservices, including REST controllers, dependency injection, configuration, and service discovery annotations. Each annotation is explained with practical examples to help you understand their usage in real-world scenarios.
Why Annotations Matter in Microservices:
- Reduced Configuration: Annotations eliminate the need for XML configuration files
- Code Clarity: Annotations make the code more readable and self-documenting
- Dependency Injection: Enable automatic dependency injection and component scanning
- RESTful APIs: Simplify the creation of REST endpoints
- Configuration Management: Externalize configuration for different environments
@RestController
Combines @Controller and @ResponseBody. It indicates that a class is a Spring MVC controller where every method returns a domain object instead of a view.
@RestController
@RequestMapping("/api")
public class MyController {
@GetMapping("/hello")
public String sayHello() {
return "Hello, World!";
}
}
@RequestMapping
Used to map web requests to a specific handler class or method. It can be applied at the class or method level.
@RestController
@RequestMapping("/api")
public class MyController {
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String sayHello() {
return "Hello, World!";
}
}
@GetMapping
A shortcut for @RequestMapping with method=RequestMethod.GET. Used for handling GET requests.
@RestController
public class MyController {
@GetMapping("/hello")
public String sayHello() {
return "Hello, World!";
}
}
@PostMapping
A shortcut for @RequestMapping with method=RequestMethod.POST. Used for handling POST requests.
@RestController
public class MyController {
@PostMapping("/create")
public String create(@RequestBody String data) {
return "Data created: " + data;
}
}
@PutMapping
A shortcut for @RequestMapping with method=RequestMethod.PUT. Used for handling PUT requests.
@RestController
public class MyController {
@PutMapping("/update")
public String update(@RequestBody String data) {
return "Data updated: " + data;
}
}
@DeleteMapping
A shortcut for @RequestMapping with method=RequestMethod.DELETE. Used for handling DELETE requests.
@RestController
public class MyController {
@DeleteMapping("/delete/{id}")
public String delete(@PathVariable("id") String id) {
return "Deleted ID: " + id;
}
}
@PathVariable
Used to extract values from the URI and bind them to method parameters.
@RestController
public class MyController {
@GetMapping("/user/{id}")
public String getUserById(@PathVariable("id") String id) {
return "User ID: " + id;
}
}
@RequestBody
Maps the body of the HTTP request to a Java object. Useful for handling JSON data.
@RestController
public class MyController {
@PostMapping("/create")
public String createUser(@RequestBody User user) {
return "User created: " + user.getName();
}
}
class User {
private String name;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
@RequestParam
Used to extract query parameters from the URL.
@RestController
public class MyController {
@GetMapping("/greet")
public String greet(@RequestParam("name") String name) {
return "Hello, " + name;
}
}
@ExceptionHandler
Used to handle exceptions in a specific controller or globally.
@RestController
@ControllerAdvice
public class ExceptionController {
@ExceptionHandler(Exception.class)
public String handleException(Exception e) {
return "Error: " + e.getMessage();
}
}
@CrossOrigin
Enables cross-origin resource sharing (CORS).
@RestController
@CrossOrigin(origins = "http://example.com")
public class MyController {
@GetMapping("/data")
public String getData() {
return "Data";
}
}
<
Summary
Understanding and properly using these annotations is essential for building robust Spring Boot microservices. These annotations provide a declarative way to configure your application, reducing boilerplate code and improving code readability. When building microservices, always consider:
- RESTful Design: Use appropriate HTTP method annotations (@GetMapping, @PostMapping, etc.)
- Dependency Injection: Leverage @Autowired, @Component, @Service, and @Repository for loose coupling
- Configuration: Use @ConfigurationProperties and @Value for externalized configuration
- Error Handling: Implement @ExceptionHandler and @ControllerAdvice for centralized exception handling
- Security: Apply @PreAuthorize and @Secured for method-level security
By mastering these annotations, you'll be able to build scalable, maintainable microservices that follow Spring Boot best practices and are ready for production deployment.