1. Spring (Core) Annotations
@Component
Definition: Marks a class as a Spring-managed component.
Usage: Used for any generic component that needs to be auto-detected and registered in the application context.
Example:
@Controller
Definition: Indicates a class is a Spring MVC controller to handle web requests.
Usage: Used in Spring MVC applications to define a web layer controller that returns views.
Example:
@Service
Definition: Specialized @Component
used for service layer classes.
Usage: Used to indicate a class contains business logic.
Example:
@Repository
Definition: Specialized @Component
used for persistence layer components.
Usage: Enables automatic exception translation from JPA/Hibernate exceptions to Spring DataAccessException.
Example:
@Configuration
Definition: Marks a class as a source of Spring bean definitions.
Usage: Used to define beans via Java-based configuration.
Example:
@Bean
Definition: Declares a method that returns a bean to be managed by Spring.
Usage: Used inside @Configuration
-annotated classes to explicitly define beans.
Example:
@Autowired
Definition: Injects a dependency automatically by type.
Usage: Used to auto-wire beans into a class’s fields or constructors.
Example:
@Qualifier
Definition: Specifies the exact bean to inject when multiple candidates are present.
Usage: Used with @Autowired
to resolve ambiguity.
Example:
@Primary
Definition: Indicates that a bean should be given preference during autowiring.
Usage: Used when multiple beans of the same type exist, but one should be the default.
Example:
@Value
Definition: Injects a value from the properties file or expression.
Usage: Used to inject configuration values directly into beans.
Example:
@Scope
Definition: Defines the lifecycle scope of a bean (singleton, prototype, request, etc.).
Usage: Used to create non-singleton beans.
Example:
@Lazy
Definition: Delays bean initialization until it is actually needed.
Usage: Improves startup performance by lazy loading non-critical beans.
Example:
@PostConstruct
Definition: Marks a method to be executed after the bean is initialized.
Usage: Used for initialization logic after dependency injection.
Example:
@PreDestroy
Definition: Marks a method to be called before the bean is destroyed.
Usage: Used for cleanup logic before the bean is removed.
Example:
2. Spring MVC (Web Layer) Annotations
@RequestMapping
Definition: Maps a specific HTTP request to a method in a controller.
Usage: Can be used for class-level or method-level URL mappings.
Example:
@GetMapping, @PostMapping, @PutMapping, @PatchMapping, @DeleteMapping
Definition: Shorthand for @RequestMapping
with specific HTTP methods.
Usage: Used to handle RESTful requests.
Example:
@RequestParam
Definition: Binds a request parameter to a method argument.
Usage: Used to extract query parameters from a request.
Example:
@PathVariable
Definition: Binds a URI path variable to a method parameter.
Usage: Used to extract dynamic segments from the URL.
Example:
@RequestBody
Definition: Binds the body of an HTTP request to an object.
Usage: Used for handling JSON/XML payloads.
Example:
@ResponseBody
Definition: Indicates that the return value should be used as the response body.
Usage: Typically used in REST APIs to return JSON/XML.
Example:
@RestController
Definition: A shortcut for @Controller
+ @ResponseBody
.
Usage: Used to create RESTful web services.
Example:
@RequestHeader
Definition: Binds a method parameter to an HTTP header.
Usage: Used to access request headers.
Example:
@CookieValue
Definition: Binds a method parameter to a cookie value.
Usage:
Used to read cookies.
Example:
@SessionAttribute
Definition: Binds a method parameter to a session attribute.
Usage: Used to retrieve session-scoped data.
Example:
@ModelAttribute
Definition: Binds request parameters to model attributes or adds attributes to the model.
Usage: Used in both controllers and methods to prepopulate form data.
Example:
@InitBinder
Definition: Customizes data binding for request parameters.
Usage: Used to register custom editors or formatters.
Example:
@ExceptionHandler
Definition: It handle exceptions thrown by controller methods so instead of returning an error page or stack trace, you can customize the response (via @ControllerAdvice
or @RestControllerAdvice
).
Example: If this exception happens in a controller, run this method instead of crashing!
@RestController
public class UserController {
@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id) {
// Simulate user not found
throw new UserNotFoundException("User not found with ID: " + id);
}
}
- Without @ExceptionHandler, Spring will return a 500 error and a big stack trace.
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<String> handleUserNotFound(UserNotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(ex.getMessage());
}
}
- Now, when UserNotFoundException is thrown:
- It doesn’t crash the app.
- Spring calls handleUserNotFound() method.
- The client receives a 404 Not Found response with a friendly message.
- Your custom exception class
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(String message) {
super(message);
}
}
Spring-Specific? Yes
- You can define different methods for different exceptions (Multiple Exception Handlers)
@ExceptionHandler(NullPointerException.class)
public ResponseEntity<String> handleNPE(NullPointerException ex) {
return ResponseEntity.status(400).body("Null error: " + ex.getMessage());
}
@ExceptionHandler(RuntimeException.class)
public ResponseEntity<String> handleRuntime(RuntimeException ex) {
return ResponseEntity.status(500).body("Unexpected error occurred");
}
Tip: Use @RestControllerAdvice
for APIs that return JSON, and @ControllerAdvice
for apps that return views (HTML pages).
@ControllerAdvice
Definition: Marks a class as a global exception handler, data binder, or model attribute provider for all controllers.
Usage: Use this to centralize exception handling logic.
Example:
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<String> handleIllegalArg(IllegalArgumentException e) {
return ResponseEntity.badRequest().body("Invalid input");
}
}
Spring-Specific? Yes
@RestControllerAdvice
Definition: A composed annotation combining @ControllerAdvice
and @ResponseBody
. Suitable for REST APIs.
Usage: Used to return JSON/XML responses instead of view names when exceptions occur.
Example:
@RestControllerAdvice
public class ApiExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleException(Exception e) {
return ResponseEntity.status(500).body("Server Error: " + e.getMessage());
}
}
Spring-Specific? Yes
3. Spring Boot Annotations
@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan
@ConfigurationProperties
@SpringBootTest
@TestConfiguration
@RequestScope, @SessionScope, @ApplicationScope
4. Spring Data & Persistence Annotations
@Entity
Definition: Marks a class as a JPA entity that maps to a database table.
Usage: Used to indicate a class should be persisted in a relational database.
Example:
@Table
Definition: Specifies the table name mapped to the entity.
Usage: Used to customize the table name or schema.
Example:
@Id
Definition: Marks a field as the primary key.
Usage: Mandatory for each entity to uniquely identify records.
Example:
@GeneratedValue
Definition: Specifies how the primary key should be generated.
Usage: Used in combination with @Id
.
Example:
@Column
Definition: Customizes mapping of a field to a column.
Usage: Used to define column properties like name, length, nullable, etc.
Example:
@Transient
Definition: Prevents a field from being persisted to the database.
Usage: Useful for temporary or calculated fields.
Example:
@Lob
Definition: Maps a large object (CLOB/BLOB) to the database.
Usage: Used for large text or binary content.
Example:
@Temporal
Definition: Specifies the format for java.util.Date
persistence.
Usage: Used with legacy Date
or Calendar
objects.
Example:
@OneToOne, @OneToMany, @ManyToOne, @ManyToMany
Definition: Define relationships between JPA entities.
Usage: Used to model associations in object-relational mapping.
Example:
@JoinColumn
Definition: Specifies the foreign key column for relationships.
Usage: Used with associations to define how tables are joined.
Example:
@MappedSuperclass
Definition: Indicates a class whose fields are inherited by entities, but not a table itself.
Usage: For base classes that share common fields like audit info.
Example:
@Embeddable, and @Embedded
Definition: Used to create component objects inside entities (value objects).
Usage: Used to group fields into reusable embeddable objects.
Example:
@Query
Definition: Defines custom JPQL or native SQL queries on a repository method.
Usage: Used when the default query derivation is not enough.
Example:
@Modifying
Definition: Used on @Query
methods that change data (e.g., update, delete).
Usage: Tells Spring Data the query modifies data and is not read-only.
Example:
@Param
Definition: Maps method parameters to query named parameters.
Usage: Used inside @Query
statements.
Example:
@EnableJpaRepositories
Definition: Enables JPA repositories by scanning packages.
Usage: Placed on a configuration class to activate Spring Data JPA support.
Example:
@RepositoryRestResource
Definition: Exposes a Spring Data JPA repository as a REST endpoint.
Usage: Used in Spring Data REST projects.
Example:
@Transactional
@EnableTransactionManagement
@Lock
5. Spring Caching Annotations
@EnableCaching
@Cacheable
@CachePut
@CacheEvict
@Caching
6. Spring AOP Annotations
@Aspect
@Before, @After, @AfterReturning, @AfterThrowing, @Around
@Pointcut
7. Spring Scheduling & Async Execution Annotations
@EnableScheduling
@Scheduled
@EnableAsync
@Async
8. Spring Security Annotations
@EnableWebSecurity
Definition: Enables Spring Security’s web security support and allows customization via a WebSecurityConfigurerAdapter
.
Usage: Placed on a configuration class to activate Spring Security's auto-configuration for web applications.
Example:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated();
}
}
Spring-Specific? Yes
@Secured
Definition: Restricts method access to users who have specific roles.
Usage: Used on service or controller methods to allow access only to users with given roles.
Example:
Spring-Specific? No (Part of JSR-250, but enabled in Spring via @EnableGlobalMethodSecurity
)
@RolesAllowed
Definition: Similar to @Secured
; defines roles that are allowed to access a method.
Usage: Used to restrict access using role-based authorization.
Example:
Spring-Specific? No (Standard JSR-250 annotation, supported in Spring with config)
@PreAuthorize
Definition: Evaluates a SpEL (Spring Expression Language) expression before method execution to determine access.
Usage: Used for fine-grained access control on service methods or controller endpoints.
Example:
Spring-Specific? Yes
@PostAuthorize
Definition: Evaluates a SpEL expression after method execution to determine whether access should be allowed.
Usage: Used when you want to verify permissions after the method returns something (like a domain object).
Example:
Spring-Specific? Yes
@PreFilter (less common)
Definition: Filters a collection of input values before the method executes using SpEL.
Usage: Used to restrict what arguments go into a method.
Example:
Spring-Specific? Yes
@PostFilter (less common)
Definition: Filters the return collection after method execution based on SpEL.
Usage: Used when you want to return only items a user is allowed to see.
Example:
Spring-Specific? Yes
@EnableGlobalMethodSecurity
Definition: Enables method-level security annotations like @Secured
, @PreAuthorize
, @PostAuthorize
.
Usage: Must be declared in a configuration class to activate those annotations.
Example:
Spring-Specific? Yes
9. Spring Validation Annotations
@Valid
Definition: Triggers JSR-303 validation on a field, method parameter, or return value.
Usage: Use in controller method parameters or bean fields to trigger validation automatically.
Example (in a controller):
Spring-Specific? No (Standard JSR-303, supported by Spring)
@Validated
Definition: Spring-specific annotation that supports validation groups in addition to JSR-303 validation.
Usage: Used on classes or method parameters to validate beans with group-based rules.
Example (in a service or controller):
Spring-Specific? Yes
@NotNull
Definition: Validates that the annotated value is not null
.
Usage: Used on fields where null values are not acceptable.
Example:
Spring-Specific? No (JSR-303 standard)
@NotBlank
Definition: Validates that the annotated string is not null
and is not empty after trimming.
Usage: Used for validating non-empty text inputs.
Example:
Spring-Specific? No (JSR-303 / Hibernate Validator)
@NotEmpty
Definition: Validates that a collection, map, or string is not null
and not empty.
Usage: Used for validating lists or strings that must have at least one element or character.
Example:
Spring-Specific? No
@Size
Definition: Validates that the size of a string, collection, or array falls within given bounds.
Usage: Used to restrict the number of characters or elements.
Example:
Spring-Specific? No
@Email
Definition: Validates that a string is a well-formed email address.
Usage: Used for email field validation.
Example:
Spring-Specific? No (Provided by Hibernate Validator)
@Min/@Max
Definition: Validates that a number is greater than (@Min
) or less than (@Max
) a given value.
Usage: Used for numerical range constraints.
Example:
Spring-Specific? No
@Pattern
Definition: Validates that a string matches a given regular expression.
Usage: Used to enforce format constraints like alphanumeric, phone numbers, etc.
Example:
Spring-Specific? No
@AssertTrue/@AssertFalse
Definition: Validates that a boolean field is true
or false
.
Usage: Used when certain boolean flags must meet a specific value.
Example:
Spring-Specific? No
@Past/@Future
Definition: Validates that a date/time is in the past or future.
Usage: Used for validating birth dates, expiration dates, etc.
Example:
Spring-Specific? No
@Constraint
Definition: Marks an annotation as a custom validation constraint.
Usage: Used to create custom validators (e.g., @ValidPhoneNumber, @ValidCurrency).
Example:
Spring-Specific? No (JSR-303, but fully usable in Spring)
10. Spring Conditional & Profile Based Annotations
@Profile
Definition: Activates a component only if the specified Spring profile is active.
Usage: Use this to register beans conditionally based on the environment (e.g., dev
, test
, prod
).
Example:
In application.properties
:
@Conditional
Definition: Registers a bean conditionally based on custom logic encapsulated in a Condition
class.
Usage: Use this when complex or custom runtime conditions should decide if a bean should be loaded.
Example:
Custom condition:
@ConditionalOnProperty (Spring Boot)
Definition: Registers a bean only if a specific property is set to a desired value.
Usage: Use for feature toggles or bean activation via configuration.
Example:
In application.properties
:
@ConditionalOnMissingBean (Spring Boot)
Definition: Registers a bean only if the specified bean is not already present in the Spring context.
Usage: Useful to provide default implementations that can be overridden by user-defined beans.
Example:
@ConditionalOnBean (Spring Boot)
Definition: Registers a bean only if a specified bean already exists in the context.
Usage: Used for dependent bean creation when another bean must exist.
Example:
@ConditionalOnClass (Spring Boot)
Definition: Registers a bean only if the specified class is available on the classpath.
Usage: Useful for auto-configuration modules that depend on optional libraries.
Example:
@ConditionalOnExpression (Spring Boot)
Definition: Registers a bean conditionally based on a SpEL (Spring Expression Language) expression.
Usage: Used for flexible configuration using expressions.
Example:
@ActiveProfiles
Definition: Specifies active Spring profiles when running a test.
Usage: Used in Spring Boot tests to simulate different runtime environments.
Example:
@ProfileGroups (Spring Boot 2.4+)
Definition: Defines logical groupings of Spring profiles that activate multiple profiles under one name.
Usage: Simplifies environment configuration by grouping related profiles.
Example (application.yml):
Then in properties:
(All profiles in the group will be activated.)
@ImportResource
@Configuration
@ImportResource("classpath:applicationContext.xml")
public class AppConfig {
}
@DependsOn
@PropertySource
@PostConstruct
Definition: Marks a method to be invoked after the bean is constructed and all dependencies have been injected.
Usage: Use for initialization logic like validating config values, starting background tasks, or setting up connections.
Example:
Spring-Specific? No (Part of JSR-250, but fully supported by Spring)
@PreDestroy
Definition: Marks a method to be called before the Spring bean is destroyed.
Usage: Use for resource cleanup, e.g., closing files, DB connections, or stopping threads.
Example:
Spring-Specific? No (Part of JSR-250, but supported by Spring)
@Required (deprecated)
Definition: Marks a bean property as required — Spring will fail to load the application context if it’s not set.
Usage: Was used to enforce property injection via setter methods. Now deprecated in favor of constructor injection.
Example:
Spring-Specific? Yes (Only exists in Spring; deprecated since Spring 5)
@Lookup
Definition: Marks a method to be overridden by Spring to return a new instance of a bean — typically a prototype bean.
Usage: Use when a singleton bean needs to dynamically access a prototype-scoped bean.
Example:
Spring-Specific? Yes (Introduced by Spring)
@Inject
Definition: Injects a dependency by type, similar to @Autowired
.
Usage: Used as a standard alternative to @Autowired
, especially in Jakarta EE / Javax environments.
Example:
Spring-Specific? No (Part of JSR-330, but fully supported by Spring)
@Resource
Definition: Injects a bean by name (preferred) or by type if name is not found.
Usage: Use when you want to inject beans by their exact name (legacy or XML-style compatibility).
Example:
Spring-Specific? No (Part of JSR-250, supported by Spring)
13. Spring Miscellaneous Annotations
@Order
Definition: Defines the execution order of components (aspects, filters, interceptors, etc.).
Usage: Used to control ordering when multiple components of the same type are present.
Example:
@Order(1)
@Component
public class FirstInterceptor implements HandlerInterceptor { }
Spring-Specific? Yes
@ConditionalOnJava
Definition: Loads a bean only if the application is running on a specified Java version or later.
Usage: Used in Spring Boot auto-configuration classes.
Example:
@Configuration
@ConditionalOnJava(JavaVersion.EIGHT)
public class Java8Config {
}
Spring-Specific? Yes (Spring Boot)
@ConditionalOnWebApplication
Definition: Loads a bean only in a web application context.
Usage: Used in auto-configuration modules.
Example:
@Configuration
@ConditionalOnWebApplication
public class WebOnlyConfig {
}
Spring-Specific? Yes