Skip to content

Most Used Spring Boot & Microservices Annotations

A comprehensive reference of the most important annotations grouped by category.


Core / Application Bootstrap

@SpringBootApplication

The entry point of any Spring Boot app. Combines @Configuration, @EnableAutoConfiguration, and @ComponentScan. Applied to the main class.

@EnableAutoConfiguration

Tells Spring Boot to auto-configure beans based on classpath dependencies. Rarely used directly since @SpringBootApplication includes it.

@ComponentScan

Instructs Spring to scan a package (and sub-packages) for components. Useful when you have non-standard package structures.

@Configuration

Create a bean with a specific configuration, and Spring will use it as defined. This differs from auto configuration because with auto configuration, it tells Spring to use it if any other bean is not present.


Stereotype / Bean Declaration

@Component

Generic Spring-managed bean. Parent of all stereotype annotations.

@Service

Marks a class as a service layer component. Semantically indicates business logic.

@Repository

Marks a class as a data access layer component. Also enables Spring's persistence exception translation.

@Controller

Marks a class as a Spring MVC controller (returns views). Often replaced by @RestController in APIs.

@RestController

Combines @Controller + @ResponseBody. Every method returns a response body (JSON/XML) directly — the most-used annotation in REST microservices.

@Configuration (Bean Source)

Marks a class as a source of bean definitions (replaces XML config).

@Bean

Declares a method's return value as a Spring-managed bean, used inside @Configuration classes.


Web / REST Mapping

@RequestMapping

Maps HTTP requests to handler methods/classes — the base annotation for URL mapping.

@GetMapping / @PostMapping / @PutMapping / @DeleteMapping / @PatchMapping

Shorthand composed annotations for each HTTP method. @GetMapping and @PostMapping are by far the most common.

@PathVariable

Binds a URI template variable to a method parameter. e.g., /users/{id}.

@RequestParam

Binds a query parameter to a method parameter. e.g., ?page=1&size=10.

@RequestBody

Deserializes the HTTP request body (JSON) into a Java object.

@ResponseBody

Serializes the return value of a method to the HTTP response body.

@ResponseStatus

Sets the HTTP status code for a response, commonly used on exception handlers.


Dependency Injection

@Autowired

Injects a Spring bean by type. Can be used on constructors, fields, or setters. Constructor injection is the modern best practice.

@Qualifier

Used alongside @Autowired to disambiguate when multiple beans of the same type exist.

@Value

Injects values from application.properties / application.yml or SpEL expressions. e.g., @Value("${server.port}").


Configuration & Profiles

@ConfigurationProperties

Binds a group of properties from config files to a POJO. Much cleaner than many individual @Value fields.

@ConfigurationProperties(prefix = "app.mail")
public class MailProperties {
    private String host;
    private int port;
    private String username;
    // getters and setters
}
# application.yml
app:
  mail:
    host: smtp.example.com
    port: 587
    username: admin

@Profile

Activates a bean or configuration only for specific Spring profiles (e.g., dev, prod).


Security (Spring Security)

@EnableWebSecurity

Enables Spring Security's web security support.

@PreAuthorize

Method-level security — evaluates a SpEL expression before the method runs. e.g., @PreAuthorize("hasRole('ADMIN')").



Microservice-Specific Annotations


Service Discovery & Registration (Spring Cloud Netflix / Eureka)

@EnableEurekaServer

Turns your Spring Boot app into a Eureka Service Registry. Applied on the main class of your discovery server.

@EnableDiscoveryClient

Registers your microservice with any discovery server (Eureka, Consul, Zookeeper). The more generic alternative to @EnableEurekaClient.

@EnableEurekaClient

Specifically registers with a Eureka server. Functionally similar to @EnableDiscoveryClient but Eureka-specific.


API Gateway (Spring Cloud Gateway)

@EnableZuulProxy (legacy, pre-Boot 3)

Turns the app into a Zuul API Gateway with routing and filtering. Largely replaced by Spring Cloud Gateway in modern stacks.


Inter-Service Communication (OpenFeign)

@EnableFeignClients

Applied on the main class — tells Spring to scan for @FeignClient interfaces and generate implementations.

@FeignClient

Declares a declarative REST client. You define an interface and Spring generates the HTTP call implementation. The most important microservice communication annotation.

@FeignClient(name = "order-service", url = "${order.service.url}")
public interface OrderClient {
    @GetMapping("/orders/{id}")
    OrderDTO getOrder(@PathVariable Long id);
}

Fault Tolerance & Resilience (Resilience4j)

@CircuitBreaker

Wraps a method with a circuit breaker — stops calls to a failing downstream service and falls back gracefully.

@CircuitBreaker(name = "orderService", fallbackMethod = "fallback")
public OrderDTO getOrder(Long id) { ... }

@Retry

Automatically retries a failed method call a configurable number of times before giving up.

@RateLimiter

Limits how many calls per time window are allowed — protects downstream services from being overwhelmed.

@Bulkhead

Isolates failures by limiting concurrent calls to a service, preventing one slow dependency from exhausting all threads.

@TimeLimiter

Sets a timeout on a method — if it doesn't complete in time, a fallback is triggered.


Configuration Management (Spring Cloud Config)

@EnableConfigServer

Turns your app into a centralized Spring Cloud Config Server that serves configuration to other microservices.

@RefreshScope

Marks a bean to be refreshed at runtime when config changes — triggers via /actuator/refresh. Critical for dynamic config without restarts.

@RefreshScope
@RestController
public class GreetingController {
    @Value("${greeting.message}")
    private String message;
}

Messaging (Kafka / RabbitMQ)

@EnableKafka

Enables Kafka listener support in the application context. Required to use @KafkaListener.

@KafkaListener

Marks a method as a Kafka message consumer for a specific topic.

@KafkaListener(topics = "orders", groupId = "inventory-group")
public void consume(String message) { ... }

@KafkaHandler

Used inside a @KafkaListener class to route different message types to different methods.

@EnableRabbit

Enables RabbitMQ listener support. Required for @RabbitListener.

@RabbitListener

Marks a method as a RabbitMQ message consumer for a specific queue.

@RabbitListener(queues = "order.queue")
public void handleOrder(OrderEvent event) { ... }

Security (Spring Security + OAuth2)

@EnableResourceServer (Spring Security OAuth2, legacy)

Marks the app as an OAuth2 resource server that validates tokens. Replaced by @EnableWebSecurity + oauth2ResourceServer() config in Boot 3.x.

@EnableAuthorizationServer (legacy)

Turns the app into an OAuth2 Authorization Server. Replaced by Spring Authorization Server project in modern stacks.

@PreAuthorize (Microservices)

Method-level security using SpEL. Used heavily in microservices to enforce role/scope-based access.

@PreAuthorize("hasAuthority('SCOPE_read:orders')")
public List<Order> getAllOrders() { ... }

Observability & Monitoring (Actuator / Micrometer)

@EnableScheduling

Enables Spring's task scheduling. Used in microservices for health checks, polling, and scheduled jobs.

@Timed (Micrometer)

Automatically records method execution time as a Micrometer metric, exported to Prometheus/Grafana.

@Timed(value = "order.fetch.time", description = "Time to fetch orders")
public List<Order> getOrders() { ... }

Distributed Tracing (Spring Cloud Sleuth / Micrometer Tracing)

@NewSpan

Creates a new distributed trace span for a method — used to track execution across microservice boundaries in Zipkin/Jaeger.

@NewSpan("fetch-inventory")
public Inventory fetchInventory(Long productId) { ... }

Load Balancing

@LoadBalanced

Applied to a RestTemplate or WebClient bean — enables client-side load balancing via Spring Cloud LoadBalancer, distributing calls across multiple instances of a service.

@Bean
@LoadBalanced
public RestTemplate restTemplate() {
    return new RestTemplate();
}

Quick Reference Map

Concern Key Annotations
Service Discovery @EnableEurekaServer, @EnableDiscoveryClient
Inter-Service Calls @FeignClient, @EnableFeignClients, @LoadBalanced
Fault Tolerance @CircuitBreaker, @Retry, @RateLimiter, @Bulkhead
Config Management @EnableConfigServer, @RefreshScope
Messaging @KafkaListener, @RabbitListener
Security @PreAuthorize, @EnableResourceServer
Observability @Timed, @NewSpan

Created with care by @TharinduEpaz

www.epazingha.me