Skip to main content

Chapter 5: Complete Annotation Dictionary (A-Z)

Quick reference of all Spring Boot annotations, sorted alphabetically. For detailed code examples, see chapters 1 to 4.


A​

AnnotationDescription
@ActiveProfilesActivates specific Spring profiles for unit tests. Allows loading application-test.yml for example.
@After(JUnit 4) Executes code after each test method.
@AfterClass(JUnit 4) Executes code after all test methods in a class.
@AfterEach(JUnit 5) Executes code after each test method. Replaces @After.
@AsyncExecutes a method asynchronously in a separate thread. Requires @EnableAsync.
@AutoConfigureDataJpaAutomatically configures JPA for a unit test.
@AutoConfigureJsonTestersAutomatically configures JSON serialization/deserialization tools for tests.
@AutoConfigureMockMvcAutomatically configures the MockMvc object for a unit test.
@AutoConfigureWebTestClientAutomatically configures the WebTestClient for WebFlux tests.
@AutowiredAutomatically injects a dependency (Spring bean) into a class. Prefer constructor injection.

B​

AnnotationDescription
@BeanDeclares a method that returns an object managed by the Spring container. Used in @Configuration classes.
@Before(JUnit 4) Executes code before each test method.
@BeforeClass(JUnit 4) Executes code before all test methods in a class.
@BeforeEach(JUnit 5) Executes code before each test method. Replaces @Before.

C​

AnnotationDescription
@CacheableCaches the result of a method. Subsequent calls return the cached result.
@CacheConfigConfigures cache settings (name, lifespan, max size) for an entire class.
@CacheEvictRemoves one or all cache entries when the method is called.
@CachePutUpdates the cache with the method result, never using the existing cache.
@CircuitBreaker(Spring Cloud) Protects a method from repeated failures by limiting calls when the service is down.
@ColumnConfigures the mapping of a JPA property to a database column (name, nullable, unique, length).
@ComponentMarks a class as a generic Spring bean, automatically detected by component scan.
@ComponentScanScans packages to automatically detect classes annotated with @Component, @Service, @Repository, etc.
@ConditionalConditions the creation of a bean based on a custom condition.
@ConditionalOnClassCreates a bean only if a specific class is present in the classpath.
@ConditionalOnMissingBeanCreates a bean only if no other bean of the same type already exists.
@ConditionalOnPropertyCreates a bean only if a property has a certain value in the configuration.
@ConfigurationMarks a Spring configuration class containing @Bean methods.
@ConfigurationPropertiesBinds a group of configuration file properties to a Java object (e.g., app.mail.host).
@ControllerMarks a class as a Spring MVC controller that returns views (HTML templates).
@ControllerAdviceDefines a global advisor for all controllers (centralized exception handling, binding, etc.).
@CrossOriginAllows cross-origin HTTP requests (CORS) from specific domains or all domains.

D​

AnnotationDescription
@DataJpaTestSpecialized test that loads only the JPA layer (repositories, EntityManager, in-memory DB).
@DeleteMappingShortcut for @RequestMapping(method = DELETE). Maps a method to an HTTP DELETE request.
@Disabled(JUnit 5) Temporarily disables a unit test without removing it from the code.

E​

AnnotationDescription
@EnableAsyncEnables asynchronous execution in the application. Necessary for @Async to work.
@EnableCachingEnables caching in the application. Necessary for @Cacheable to work.
@EnableConfigurationPropertiesEnables automatic binding of configuration properties to @ConfigurationProperties objects.
@EnableJmsEnables JMS (Java Message Service) support for messaging in the application.
@EnableJpaRepositoriesEnables support for Spring Data JPA repositories. Automatically configured by Spring Boot.
@EnableSchedulingEnables task scheduling. Necessary for @Scheduled to work.
@EnableWebMvcEnables Spring MVC configuration. Rarely necessary as Spring Boot enables it automatically.
@EnableWebSecurityEnables custom Spring Security configuration.
@EnableMethodSecurityEnables method-level security (@PreAuthorize, @PostAuthorize, @Secured).
@EntityMarks a class as a JPA entity, mapped to a database table.
@EnumeratedDefines how a Java enum is stored in the DB: STRING (text) or ORDINAL (number).
@EventListenerListens for Spring events (application startup, custom events, etc.).
@ExceptionHandlerHandles a specific exception in a controller or @ControllerAdvice. Returns a custom error response.
@ExtendWith(JUnit 5) Extends test functionalities with extensions (e.g., SpringExtension, MockitoExtension).

F​

AnnotationDescription
@Fallback(Spring Cloud) Provides a fallback method when a @CircuitBreaker method fails.
@FlywayTestTests Flyway database migrations in integration tests.
@Formula(Hibernate) Defines a SQL-side calculated column, without a physical column in the database.

G​

AnnotationDescription
@GeneratedValueDefines the automatic generation strategy for the primary key (IDENTITY, SEQUENCE, UUID, AUTO).
@GetMappingShortcut for @RequestMapping(method = GET). Maps a method to an HTTP GET request.

I​

AnnotationDescription
@IdMarks a field as the primary key of a JPA entity.
@ImportImports other configuration classes into a @Configuration class.
@InitBinderCustomizes data binding between HTTP requests and Java objects (conversion, validation, formatting).

J​

AnnotationDescription
@JoinColumnDefines the foreign key column for a JPA relationship (@ManyToOne, @OneToOne).
@JoinTableDefines the join table for a @ManyToMany relationship (table name, join columns).
@JmsListenerDefines a method that listens for JMS messages on a queue or topic.
@JsonFormatCustomizes JSON serialization format (dates, numbers). E.g., @JsonFormat(pattern = "yyyy-MM-dd").
@JsonIgnoreExcludes a property from JSON serialization/deserialization.
@JsonIncludeControls which properties are included in JSON (e.g., exclude null values).
@JsonPropertyRenames a property in JSON. E.g., @JsonProperty("full_name") for a fullName field.
@JsonSubTypesDefines subtypes for polymorphic JSON deserialization.
@JsonTestSpecialized test for JSON serialization/deserialization only.
@JsonTypeInfoAdds type information in JSON to allow polymorphic deserialization.
@JsonViewFilters JSON properties according to the requested view (e.g., public view vs admin view).

L​

AnnotationDescription
@LazyDelays bean initialization until its first use. Improves startup time.
@LobIndicates a Large Object field: CLOB (long text) or BLOB (binary).

M​

AnnotationDescription
@ManyToManyDefines a many-to-many relationship between two JPA entities. Uses a join table.
@ManyToOneDefines a many-to-one relationship. The "Many" side holds the foreign key.
@MessageMapping(WebSocket/STOMP) Maps a method to a messaging destination.
@MessagingGateway(Spring Integration) Defines a gateway interface for sending messages.
@MockBeanReplaces a Spring bean with a Mockito mock in a test.
@MockMvcInjects a MockMvc instance to simulate HTTP requests in tests.
@ModelAttributeBinds HTTP request parameters to a Java object. Also used to add attributes to the MVC model.
@ModifyingIndicates that a @Query method executes an UPDATE or DELETE (not a SELECT).

N​

AnnotationDescription
@NamedQueryDefines a named JPQL query directly on an entity.
@NamedQueriesGroups multiple @NamedQuery on the same entity.

O​

AnnotationDescription
@OneToManyDefines a one-to-many relationship between two JPA entities. The "One" side is the parent.
@OneToOneDefines a one-to-one relationship between two JPA entities.
@OrderDefines the priority order of a bean. The smaller the number, the higher the priority.

P​

AnnotationDescription
@PatchMappingShortcut for @RequestMapping(method = PATCH). Partial update of a resource.
@PathVariableExtracts a variable from the URL path. E.g., /users/\{id\} → @PathVariable Long id.
@PostAuthorizeChecks authorizations after method execution (can check the returned value).
@PostConstructExecutes a method just after all bean dependencies are injected.
@PostMappingShortcut for @RequestMapping(method = POST). Creation of a new resource.
@PreAuthorizeChecks authorizations before method execution. Supports SpEL expressions.
@PreDestroyExecutes a method just before the bean is destroyed (cleanup, closing connections).
@PrimaryDefines the default bean when multiple beans of the same type exist.
@ProfileActivates a bean or configuration only for certain profiles (dev, test, prod).
@PutMappingShortcut for @RequestMapping(method = PUT). Full replacement of a resource.

Q​

AnnotationDescription
@QualifierSpecifies which bean to inject when multiple beans of the same type exist.
@QueryDefines a custom JPQL or native SQL query on a repository method.

R​

AnnotationDescription
@RepositoryMarks a class as a data access layer. Enables SQL exception translation to Spring exceptions.
@RequestBodyDeserializes the HTTP request body (JSON) into a Java object.
@RequestHeaderExtracts the value of an HTTP header (Authorization, Content-Type, User-Agent, etc.).
@RequestMappingBase annotation to map a URL to a controller or method. Can specify the HTTP method.
@RequestParamExtracts a parameter from the query string. E.g., /search?name=Java → @RequestParam String name.
@RequestPartExtracts a part of a multipart HTTP request (files, uploaded images).
@ResponseBodyForces a method to return JSON/XML directly in the HTTP response body.
@ResponseStatusDefines the HTTP status code returned by a method (200, 201, 204, 404, etc.) or an exception.
@RestClientTestSpecialized test for REST clients. Loads only the client configuration.
@RestControllerCombination of @Controller + @ResponseBody. Each method returns JSON directly.
@RestControllerAdviceCombination of @ControllerAdvice + @ResponseBody. Global exception handling for REST APIs.
@Retryable(Spring Retry) Automatically retries a method in case of failure (e.g., network or DB error).
@RolesAllowed(JSR-250) Specifies allowed roles for a method. Standard alternative to @Secured.

S​

AnnotationDescription
@ScheduledSchedules periodic execution of a method (fixedRate, fixedDelay, cron). Requires @EnableScheduling.
@ScopeDefines the scope of a bean: singleton (default), prototype, request, session, application.
@SecuredSpecifies required roles to access a method. Simpler than @PreAuthorize.
@SendTo(WebSocket/STOMP) Specifies the response destination for a WebSocket message.
@ServiceMarks a class as a business logic layer. Detected by component scan.
@SessionAttributesStores model attributes in the HTTP session between requests.
@SessionScopeDefines the scope of a bean as HTTP session (one bean per user session).
@SpyBeanWraps a real bean with a Mockito spy in tests (real calls except those stubbed).
@SpringBootApplicationApplication entry point. Combines @Configuration, @EnableAutoConfiguration, and @ComponentScan.
@SpringBootTestLoads the full Spring context for integration tests.
@SqlExecutes SQL scripts before or after a test to prepare or clean the database.

T​

AnnotationDescription
@TableCustomizes the table name, schema, uniqueness constraints, and indexes for a JPA entity.
@Test(JUnit) Marks a method as a unit test.
@TestConfigurationProvides Spring configuration specific to tests (test beans, mocks).
@Timeout(JUnit 5) Sets a maximum execution time for a test. The test fails if the time is exceeded.
@TransactionalManages DB transactions. Commits on success, rolls back on exception. readOnly = true optimizes reads.
@TransactionalEventListenerListens for a Spring event and executes it only after the transaction commit (or rollback).
@TransientExcludes a field from JPA persistence (no database column).

V​

AnnotationDescription
@ValidEnables Bean Validation on an object (@NotNull, @Size, @Email, etc.).
@ValidatedSpring variant of @Valid with support for validation groups.
@ValueInjects a value from the configuration file. E.g., @Value("${app.name}"). Supports default values and SpEL.
@ValueSource(JUnit 5) Provides input values to a parameterized test.

W​

AnnotationDescription
@WebFluxTestSpecialized test for WebFlux controllers (reactive programming).
@WebMvcTestSpecialized test that loads only the MVC controller layer (no DB, no real services).
@WebTestClientInjects a WebTestClient to simulate HTTP requests in WebFlux tests.

Validation Annotations (Bean Validation)​

AnnotationDescription
@NotNullThe field cannot be null.
@NotEmptyThe field cannot be null or empty (String, Collection, Map).
@NotBlankThe field cannot be null, empty, or contain only spaces.
@Size(min, max)The size must be between min and max (String, Collection).
@Min(value)The numeric value must be greater than or equal to value.
@Max(value)The numeric value must be less than or equal to value.
@EmailThe field must be a valid email address format.
@Pattern(regexp)The field must match the given regular expression.
@PositiveThe number must be strictly positive (> 0).
@PositiveOrZeroThe number must be positive or zero (>= 0).
@NegativeThe number must be strictly negative (< 0).
@PastThe date must be in the past.
@FutureThe date must be in the future.
@DecimalMinThe decimal value must be greater than or equal to the minimum.
@DecimalMaxThe decimal value must be less than or equal to the maximum.

Statistics​

In summary

This dictionary covers 120+ annotations distributed in:

  • Core Spring: ~25 annotations (IoC, DI, configuration, lifecycle)
  • Web / REST: ~20 annotations (mapping, parameters, responses, errors)
  • Data / JPA: ~20 annotations (entities, relationships, queries, transactions)
  • JSON / Jackson: ~7 annotations (format, filter, ignore)
  • Security: ~7 annotations (config, authorization)
  • Cache: ~5 annotations (cacheable, evict, put, config)
  • Async / Scheduling: ~5 annotations
  • Test: ~25 annotations (JUnit, Spring Test, mocks)
  • Validation: ~15 annotations (Bean Validation)
  • Messaging: ~5 annotations (JMS, WebSocket)
  • Cloud / Resilience: ~3 annotations (CircuitBreaker, Retry, Fallback)

⬅️ Back to Module 17 | ⬅️ Back to home