100 Spring boot Annotations
Below is an elaborate guide to 100 Spring Boot/Spring annotations, including detailed explanations, typical use cases, and when to add each in your code.
-
@SpringBootApplication
-
Explanation: A meta-annotation that combines @Configuration (marks class as a source of bean definitions), @EnableAutoConfiguration (enables Spring Boot’s auto-configuration mechanism), and @ComponentScan (scans for components in the package). This simplifies setup by aggregating common configurations.
-
Use Case: Kickstarting a Spring Boot application with sensible defaults out of the box.
-
When to Add: On the main application class containing the
main()
method.
-
-
@SpringBootConfiguration
-
Explanation: A specialized form of @Configuration that signals Boot-specific configuration. It behaves like @Configuration but is automatically picked up by Spring Boot.
-
Use Case: Defining additional configuration classes that participate in auto-configuration.
-
When to Add: On any class intended to serve as a configuration source in a Boot application.
-
-
@EnableAutoConfiguration
-
Explanation: Tells Spring Boot to examine classpath settings, beans, and various property settings to automatically configure your application.
-
Use Case: Reducing manual bean definitions by letting Boot wire common components (e.g., DataSource, MVC, security).
-
When to Add: On a @Configuration class, typically inherited via @SpringBootApplication.
-
-
@ComponentScan
-
Explanation: Directs Spring to scan specified packages for components annotated with @Component, @Service, @Repository, and @Controller.
-
Use Case: Automatically discovering and registering beans without explicit @Bean methods.
-
When to Add: On configuration classes when component packages lie outside the main application package.
-
-
@Configuration
-
Explanation: Marks a class as a source of bean definitions; methods annotated with @Bean within this class return Spring-managed beans.
-
Use Case: Java-based configuration instead of XML.
-
When to Add: On classes where you need to manually define beans using @Bean.
-
-
@Bean
-
Explanation: Indicates that a method produces a bean to be managed by the Spring container. Method name serves as the bean ID.
-
Use Case: Customizing or overriding auto-configured beans.
-
When to Add: On factory methods inside @Configuration classes.
-
-
@Component
-
Explanation: Generic stereotype for any Spring-managed component or bean. It enables automatic detection via classpath scanning.
-
Use Case: Marking utility or helper classes as beans.
-
When to Add: On classes you want Spring to instantiate without specific stereotypes.
-
-
@Service
-
Explanation: Specialized @Component indicating a service-layer component. Improves readability and may carry additional semantic meaning.
-
Use Case: Business logic classes.
-
When to Add: On classes that implement service operations.
-
-
@Repository
-
Explanation: Specialized @Component for persistence-layer beans. It enables exception translation to Spring’s DataAccessException hierarchy.
-
Use Case: DAO classes interacting with databases.
-
When to Add: On classes handling JDBC, JPA, or other data operations.
-
-
@Controller
-
Explanation: Marks a class as a Spring MVC controller; typically returns view names to render.
-
Use Case: Web applications serving HTML pages.
-
When to Add: On classes handling HTTP requests for UI.
-
-
@RestController
-
Explanation: Combines @Controller and @ResponseBody; methods return JSON/XML directly.
-
Use Case: RESTful web services.
-
When to Add: On controllers exposing REST endpoints.
-
-
@RequestMapping
-
Explanation: Maps HTTP requests to handler methods or classes; can specify path, method, params, headers, and more.
-
Use Case: General-purpose request mapping.
-
When to Add: On controller classes or methods to define URL routes.
-
-
@GetMapping
-
Explanation: Shortcut for @RequestMapping(method = RequestMethod.GET).
-
Use Case: Handling HTTP GET requests, typically for retrieving resources.
-
When to Add: On methods that should respond to GET requests.
-
-
@PostMapping
-
Explanation: Shortcut for @RequestMapping(method = RequestMethod.POST).
-
Use Case: Handling HTTP POST requests to create new resources.
-
When to Add: On methods receiving new entity data via POST.
-
-
@PutMapping
-
Explanation: Shortcut for @RequestMapping(method = RequestMethod.PUT).
-
Use Case: Handling HTTP PUT requests to update resources fully.
-
When to Add: On methods replacing or updating entire resources.
-
-
@DeleteMapping
-
Explanation: Shortcut for @RequestMapping(method = RequestMethod.DELETE).
-
Use Case: Handling HTTP DELETE requests to remove resources.
-
When to Add: On methods deleting entities.
-
-
@PatchMapping
-
Explanation: Shortcut for @RequestMapping(method = RequestMethod.PATCH).
-
Use Case: Handling partial updates to resources.
-
When to Add: On methods applying partial changes.
-
-
@PathVariable
-
Explanation: Binds a URI template variable to a method parameter.
-
Use Case: Extracting dynamic values from URL segments.
-
When to Add: On method parameters matching
{id}
,{name}
, etc.
-
-
@RequestParam
-
Explanation: Binds query parameters or form data to method parameters.
-
Use Case: Reading parameters from URLs like
?page=2&size=10
. -
When to Add: On parameters needing request query or form values.
-
-
@RequestBody
-
Explanation: Binds the HTTP request body to a method parameter, typically converting JSON/XML to Java objects.
-
Use Case: Consuming JSON payloads in REST APIs.
-
When to Add: On parameters expecting a request payload mapping.
-
-
@ResponseBody
-
Explanation: Indicates that the return value of a method should be used as the response body.
-
Use Case: Returning data directly without rendering a view.
-
When to Add: On methods in @Controller that return JSON/XML.
-
-
@RequestHeader
-
Explanation: Binds a specific HTTP header value to a method parameter.
-
Use Case: Reading
Authorization
,User-Agent
, or custom headers. -
When to Add: On parameters needing header values.
-
-
@CookieValue
-
Explanation: Binds the value of an HTTP cookie to a method parameter.
-
Use Case: Reading session tokens or user preferences stored in cookies.
-
When to Add: On parameters requiring cookie data.
-
-
@MatrixVariable
-
Explanation: Binds semicolon-delimited matrix variables from the URI to method parameters.
-
Use Case: Path parameters carrying multiple values like
/orders;status=shipped;region=EU
. -
When to Add: On parameters mapping to matrix variables.
-
-
@SessionAttribute
-
Explanation: Binds an attribute from the HTTP session to a handler method parameter.
-
Use Case: Retrieving user login data or cart contents across requests.
-
When to Add: On parameters that should be fetched from the session.
-
-
@ModelAttribute
-
Explanation: Binds request parameters to a model object or exposes a method’s return value to the model.
-
Use Case: Preparing form-backing objects for views or binding form data.
-
When to Add: On methods or parameters in MVC controllers handling forms.
-
-
@InitBinder
-
Explanation: Customizes the WebDataBinder used to bind request parameters to objects, allowing formatters and validators.
-
Use Case: Registering custom editors for date formats or nested properties.
-
When to Add: On methods inside controllers to configure data binding.
-
-
@ExceptionHandler
-
Explanation: Specifies a method to handle specific exceptions thrown by controller methods.
-
Use Case: Returning custom error responses for
NotFoundException
,ValidationException
, etc. -
When to Add: On methods in @Controller or @ControllerAdvice classes.
-
-
@ControllerAdvice
-
Explanation: Defines global exception handlers, data binders, and model attributes for multiple controllers.
-
Use Case: Centralizing error handling and common model attributes.
-
When to Add: On classes that should intercept exceptions across all controllers.
-
-
@RestControllerAdvice
-
Explanation: Combines @ControllerAdvice with @ResponseBody; methods return JSON/XML error payloads.
-
Use Case: Providing uniform REST error responses.
-
When to Add: On global error-handler classes for REST APIs.
-
-
@Autowired
-
Explanation: Marks a constructor, field, setter method, or config method to be autowired by Spring’s dependency injection facilities.
-
Use Case: Automatically inject required beans without manual lookup.
-
When to Add: On fields, constructors, or setter methods of classes requiring Spring-managed beans.
-
-
@Qualifier
-
Explanation: Used in conjunction with @Autowired to differentiate between multiple bean candidates of the same type.
-
Use Case: Selecting a specific implementation when more than one bean of the same type exists.
-
When to Add: Alongside @Autowired when you have multiple beans of the same type.
-
-
@Value
-
Explanation: Injects values into fields or method parameters from property files, system properties, or expressions.
-
Use Case: Externalized configuration for literals, lists, maps, or SpEL expressions.
-
When to Add: On fields or constructor parameters for config values like ${app.timeout}.
-
-
@Primary
-
Explanation: Marks a bean as the primary candidate when multiple beans match a type during autowiring.
-
Use Case: Defining a default bean without using @Qualifier everywhere.
-
When to Add: On one bean definition to resolve ambiguity among beans of the same type.
-
-
@Scope
-
Explanation: Specifies the scope of a bean—singleton, prototype, request, session, application, or custom.
-
Use Case: Controlling bean lifecycle and visibility in web apps.
-
When to Add: On @Component or @Bean definitions when non-singleton scope is required.
-
-
@Lazy
-
Explanation: Defers initialization of a bean until it is first requested, rather than at startup.
-
Use Case: Reducing startup time or breaking circular dependencies.
-
When to Add: On bean definitions or @Autowired injection points when lazy loading is desired.
-
-
@PostConstruct
-
Explanation: Marks a method to be executed after dependency injection is done to perform any initialization.
-
Use Case: Initializing resources or validating injected properties.
-
When to Add: On methods in managed beans for custom initialization logic.
-
-
@PreDestroy
-
Explanation: Marks a method to be executed just before the bean is removed from the container.
-
Use Case: Cleaning up resources like closing connections or releasing caches.
-
When to Add: On methods that need to run cleanup code before bean destruction.
-
-
@DependsOn
-
Explanation: Expresses bean initialization order by indicating that a bean depends on one or more other beans.
-
Use Case: Ensuring config or utility beans are initialized before dependent beans.
-
When to Add: On bean definitions requiring other beans to be ready first.
-
-
@Order
-
Explanation: Defines the sort order of components or ordered collections of beans.
-
Use Case: Ordering multiple Aspect, Filter, or Interceptor beans.
-
When to Add: On component classes or @Bean definitions when a specific order is needed.
-
-
@Import
-
Explanation: Allows importing additional @Configuration classes in the current application context.
-
Use Case: Modularizing configuration across multiple classes.
-
When to Add: On configuration classes needing to include other configurations.
-
-
@ImportResource
-
Explanation: Loads XML-based Spring bean definitions into the application context.
-
Use Case: Integrating legacy XML configurations.
-
When to Add: On @Configuration classes to import XML files like spring-beans.xml.
-
-
@PropertySource
-
Explanation: Specifies a properties file to be loaded into the Spring Environment.
-
Use Case: Loading additional or externalized property files.
-
When to Add: On @Configuration classes for custom property sources.
-
-
@ConfigurationProperties
-
Explanation: Binds a group of properties from the Spring Environment to a POJO.
-
Use Case: Type-safe configuration binding for externalized settings.
-
When to Add: On classes representing structured configuration (e.g., DataSourceProperties).
-
-
@EnableConfigurationProperties
-
Explanation: Enables support for @ConfigurationProperties-annotated beans in the context.
-
Use Case: Activating configuration properties support for bean classes.
-
When to Add: On the main application class or config classes enabling property binding.
-
-
@Profile
-
Explanation: Restricts bean registration to specific Spring profiles.
-
Use Case: Defining environment-specific beans for dev, test, and prod.
-
When to Add: On @Configuration classes or @Component beans for conditional loading.
-
-
@ConditionalOnProperty
-
Explanation: Registers a bean only when a specified property has a certain value.
-
Use Case: Feature toggles or conditional auto-config.
-
When to Add: On @Bean or @Configuration classes to conditionally enable features.
-
-
@ConditionalOnClass
-
Explanation: Registers a bean only if a specific class is present on the classpath.
-
Use Case: Optional dependency auto-configuration (e.g., JPA, Redis).
-
When to Add: On auto-config classes that require certain libraries.
-
-
@ConditionalOnMissingBean
-
Explanation: Registers a bean only if no other bean of the same type is defined.
-
Use Case: Allowing user-defined beans to override auto-configuration.
-
When to Add: On auto-config @Bean methods to back off when custom beans exist.
-
-
@EnableCaching
-
Explanation: Enables Spring’s annotation-driven cache management capability.
-
Use Case: Activating caching for methods annotated with @Cacheable, @CachePut, @CacheEvict.
-
When to Add: On @Configuration classes to turn on caching support.
-
-
@Cacheable
-
Explanation: Caches the result of a method call based on its parameters.
-
Use Case: Improving performance of expensive or frequently called read methods.
-
When to Add: On service methods whose results can be cached.
-
-
@CacheEvict
-
Explanation: Removes one or more entries from the cache when the annotated method is invoked.
-
Use Case: Invalidating cache after updates or deletes.
-
When to Add: On methods that modify data and require cache invalidation.
-
-
@CachePut
-
Explanation: Updates the cache without interfering with the method execution.
-
Use Case: Ensuring cache is in sync after data modifications.
-
When to Add: On update methods that should refresh cache entries.
-
-
@EnableTransactionManagement
-
Explanation: Enables Spring’s annotation-driven transaction management capability.
-
Use Case: Activating @Transactional support in the context.
-
When to Add: On @Configuration classes that require transaction demarcation.
-
-
@Transactional
-
Explanation: Declares transactional boundaries on classes or methods; supports propagation and rollback.
-
Use Case: Managing database transactions consistently.
-
When to Add: On service methods requiring atomic operations across repositories.
-
-
@EnableScheduling
-
Explanation: Enables Spring’s scheduled task execution capability.
-
Use Case: Activating @Scheduled tasks for cron, fixed rate, or fixed delay.
-
When to Add: On @Configuration classes to enable scheduling.
-
-
@Scheduled
-
Explanation: Marks a method to be run on a schedule, using cron expressions or fixed delays.
-
Use Case: Running periodic tasks like cleanup jobs or report generation.
-
When to Add: On methods that need regular execution.
-
-
@EnableAsync
-
Explanation: Enables Spring’s asynchronous method execution capability.
-
Use Case: Activating @Async processing for non-blocking background tasks.
-
When to Add: On @Configuration classes to turn on async support.
-
-
@Async
-
Explanation: Executes a method asynchronously, returning a Future or CompletableFuture.
-
Use Case: Offloading long-running or IO-bound tasks from the main thread.
-
When to Add: On methods that should run in separate threads.
-
-
@EventListener
-
Explanation: Registers a method as an application event listener, handling published events.
-
Use Case: Decoupling components by using events for communication.
-
When to Add: On methods that should react to ApplicationEvent or custom events.
-
-
@EnableWebMvc
-
Explanation: Imports the Spring MVC configuration for web applications (not typically needed in Boot).
-
Use Case: Full control over MVC config when Boot’s defaults need overriding.
-
When to Add: On @Configuration classes in non-Boot MVC apps.
-
-
@EnableJpaRepositories
-
Explanation: Enables scanning for Spring Data JPA repository interfaces.
-
Use Case: Activating CRUD repository support for JPA entities.
-
When to Add: On @Configuration classes requiring JPA repositories.
-
-
@EnableJdbcRepositories
-
Explanation: Enables scanning for Spring Data JDBC repository interfaces.
-
Use Case: Activating repository support for Spring Data JDBC.
-
When to Add: On @Configuration classes for JDBC repository usage.
-
-
@Entity
-
Explanation: Marks a class as a JPA entity, mapping it to a database table.
-
Use Case: Defining domain model classes for ORM.
-
When to Add: On classes representing database tables.
-
-
@Table
-
Explanation: Specifies the table name and schema for a JPA entity.
-
Use Case: Customizing table mapping when entity and table names differ.
-
When to Add: On entity classes needing custom table names or catalogs.
-
-
@Column
-
Explanation: Maps a field to a column, specifying details like name, nullable, length.
-
Use Case: Custom column mapping for entity fields.
-
When to Add: On fields requiring explicit column configuration.
-
-
@Id
-
Explanation: Marks a field as the primary key of a JPA entity.
-
Use Case: Identifying the unique identifier for entities.
-
When to Add: On the primary key field of each entity.
-
-
@GeneratedValue
-
Explanation: Configures primary key generation strategy (AUTO, IDENTITY, SEQUENCE, TABLE).
-
Use Case: Automating PK generation for new entities.
-
When to Add: On @Id fields where database or sequence generation is used.
-
-
@OneToOne
-
Explanation: Defines a one-to-one association between two entities.
-
Use Case: Mapping tightly coupled entities like User–Profile.
-
When to Add: On fields representing one-to-one relationships.
-
-
@OneToMany
-
Explanation: Defines a one-to-many association, mapping a collection of entities.
-
Use Case: Mapping parent-child relationships like Department–Employees.
-
When to Add: On collections representing one-to-many relationships.
-
-
@ManyToOne
-
Explanation: Defines a many-to-one association, linking many entities to one parent.
-
Use Case: Mapping child entities to their parent like Order–Customer.
-
When to Add: On fields representing the parent in a many-to-one.
-
-
@ManyToMany
-
Explanation: Defines a many-to-many association with join table mapping.
-
Use Case: Mapping entities with bidirectional many-to-many relationships.
-
When to Add: On collections representing many-to-many relationships.
-
-
@JoinColumn
-
Explanation: Specifies the foreign key column for associations.
-
Use Case: Customizing join column name and properties.
-
When to Add: On association fields needing explicit FK details.
-
-
@Embeddable
-
Explanation: Marks a class as embeddable within an entity, meaning its fields become part of the entity table.
-
Use Case: Modeling value objects like Address or AuditInfo.
-
When to Add: On plain classes used as embedded components.
-
-
@Embedded
-
Explanation: Embeds an @Embeddable class instance into an entity.
-
Use Case: Including composite value objects within entities.
-
When to Add: On fields of entities representing embedded types.
-
-
@RepositoryRestResource
-
Explanation: Exposes a Spring Data repository as a REST resource with HAL JSON by default.
-
Use Case: Quickly creating RESTful CRUD endpoints from repositories.
-
When to Add: On repository interfaces to customize path or rel.
-
-
@RestResource
-
Explanation: Customizes export details (path, rel) of individual repository methods in REST.
-
Use Case: Renaming or hiding specific repository methods.
-
When to Add: On repository methods to adjust REST behavior.
-
-
@RequestPart
-
Explanation: Binds parts of multipart/form-data requests (e.g., files) to method parameters.
-
Use Case: Handling file uploads in REST controllers.
-
When to Add: On method parameters of type MultipartFile or custom DTO parts.
-
-
@EnableKafka
-
Explanation: Enables detection of @KafkaListener annotations on spring-managed beans.
-
Use Case: Activating Kafka consumer endpoint support.
-
When to Add: On @Configuration classes that configure Kafka listeners.
-
-
@KafkaListener
-
Explanation: Marks a method to be the target of a Kafka message listener on specified topics.
-
Use Case: Consuming messages from Kafka topics.
-
When to Add: On methods processing Kafka records.
-
-
@KafkaHandler
-
Explanation: Used within a @KafkaListener class with multiple methods to handle different payload types.
-
Use Case: Polymorphic message handling in Kafka listeners.
-
When to Add: On methods inside a class annotated with @KafkaListener to route by payload type.
-
-
@SendTo
-
Explanation: Directs the return value of a @KafkaListener method to another topic.
-
Use Case: Request-reply messaging patterns.
-
When to Add: On @KafkaListener methods that send responses to topics.
-
-
@EnableBinding
-
Explanation: Binds interfaces annotated with @Input/@Output channels to the external broker via Spring Cloud Stream.
-
Use Case: Connecting to messaging systems with minimal boilerplate.
-
When to Add: On @Configuration classes in Spring Cloud Stream applications.
-
-
@StreamListener
-
Explanation: Listens to messages on input channels defined by @EnableBinding interfaces.
-
Use Case: Annotating methods to consume message streams.
-
When to Add: On methods in classes that process messages from message brokers.
-
-
@Input
-
Explanation: Declares an input channel interface in Spring Cloud Stream bindings.
-
Use Case: Defining channel names for inbound messages.
-
When to Add: On methods in an interface annotated with @EnableBinding.
-
-
@Output
-
Explanation: Declares an output channel interface in Spring Cloud Stream bindings.
-
Use Case: Defining channel names for outbound messages.
-
When to Add: On methods in an interface annotated with @EnableBinding.
-
-
@EnableEurekaClient
-
Explanation: Enables Netflix Eureka client functionality for service registration and discovery.
-
Use Case: Microservice registration with a Eureka server.
-
When to Add: On the main application class in a Eureka-enabled microservice.
-
-
@EnableDiscoveryClient
-
Explanation: Generic service discovery annotation supporting multiple registries (Eureka, Consul, etc.).
-
Use Case: Enabling discovery in cloud-native apps.
-
When to Add: On the main class when using any supported discovery service.
-
-
@FeignClient
-
Explanation: Declares a REST client interface with built-in load balancing and service discovery.
-
Use Case: Simplifying HTTP client calls between microservices.
-
When to Add: On interfaces defining remote service methods.
-
-
@LoadBalanced
-
Explanation: Injects a load-balanced RestTemplate by contacting a Ribbon client-side load balancer.
-
Use Case: Distributing HTTP requests across service instances.
-
When to Add: On RestTemplate bean definitions in config classes.
-
-
@EnableWebSecurity
-
Explanation: Enables Spring Security’s web security support and provides a default security configuration.
-
Use Case: Securing web application endpoints.
-
When to Add: On @Configuration classes customizing web security.
-
-
@EnableGlobalMethodSecurity
-
Explanation: Enables method-level security annotations like @PreAuthorize, @PostAuthorize.
-
Use Case: Securing service or controller methods.
-
When to Add: On security config classes requiring method-level checks.
-
-
@PreAuthorize
-
Explanation: Applies an authorization expression before method execution.
-
Use Case: Checking roles, permissions, or custom conditions.
-
When to Add: On controller or service methods requiring pre-invoke security.
-
-
@PostAuthorize
-
Explanation: Applies an authorization expression after method execution, able to inspect return value.
-
Use Case: Securing based on returned object properties.
-
When to Add: On methods requiring post-invocation security checks.
-
-
@EnableOAuth2Sso
-
Explanation: Configures OAuth2 single sign-on with default login endpoints.
-
Use Case: Adding SSO support to web applications.
-
When to Add: On @Configuration classes in OAuth2 client apps.
-
-
@EnableResourceServer
-
Explanation: Configures the application as an OAuth2 resource server, securing endpoints by token validation.
-
Use Case: Protecting REST APIs with OAuth2 tokens.
-
When to Add: On @Configuration classes for resource server setup.
-
-
@EnableOAuth2Client
-
Explanation: Enables an OAuth2 client for consuming protected resources.
-
Use Case: Outbound API calls requiring OAuth2 token acquisition.
-
When to Add: On config classes needing OAuth2RestTemplate or WebClient.
-
-
@SpringBootTest
-
Explanation: Boots up the entire Spring context for integration testing.
-
Use Case: End-to-end tests verifying controller, service, and repository integration.
-
When to Add: On test classes needing full application context.
-
-
@MockBean
-
Explanation: Adds a Mockito mock to the Spring context, replacing existing beans.
-
Use Case: Isolating components by mocking dependencies in tests.
-
When to Add: On fields in @SpringBootTest classes to override beans.
-
-
@DataJpaTest
- Explanation: Configures an application slice for JPA tests, loading only JPA components.
- Use Case: Testing repository layers with in-memory databases.
- When to Add: On test classes focusing on data access logic.
Comments
Post a Comment