Spring Framework Annotations



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:

@Component
public class EmailValidator { public boolean isValid(String email) { return email.contains("@"); } }

@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:

@Controller
public class HomeController { @GetMapping("/") public String home() { return "index"; // returns view name } }

@Service

Definition: Specialized @Component used for service layer classes.

Usage: Used to indicate a class contains business logic.

Example:

@Service
public class PaymentService { public void processPayment() { // business logic here } }

@Repository

Definition: Specialized @Component used for persistence layer components.

Usage: Enables automatic exception translation from JPA/Hibernate exceptions to Spring DataAccessException.

Example:

@Repository
public class UserRepository { public void save(User user) { // save to DB } }

@Configuration

Definition: Marks a class as a source of Spring bean definitions.

Usage: Used to define beans via Java-based configuration.

Example:

@Configuration
public class AppConfig { @Bean public UserService userService() { return new UserService(); } }

@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:

@Bean
public EmailService emailService() { return new EmailService(); }

@Autowired

Definition: Injects a dependency automatically by type.

Usage: Used to auto-wire beans into a class’s fields or constructors.

Example:

@Autowired
private PaymentService paymentService;

@Qualifier

Definition: Specifies the exact bean to inject when multiple candidates are present.

Usage: Used with @Autowired to resolve ambiguity.

Example:

@Autowired
@Qualifier("paypalService") private PaymentService paymentService;

@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:

@Primary
@Bean public PaymentService defaultPaymentService() { return new PaypalService(); }

@Value

Definition: Injects a value from the properties file or expression.

Usage: Used to inject configuration values directly into beans.

Example:

@Value("${app.name}")
private String appName;

@Scope

Definition: Defines the lifecycle scope of a bean (singleton, prototype, request, etc.).

Usage: Used to create non-singleton beans.

Example:

@Scope("prototype")
@Component public class ReportGenerator { }

@Lazy

Definition: Delays bean initialization until it is actually needed.

Usage: Improves startup performance by lazy loading non-critical beans.

Example:

@Lazy
@Component public class ExpensiveComponent { }

@PostConstruct

Definition: Marks a method to be executed after the bean is initialized.

Usage: Used for initialization logic after dependency injection.

Example:

@PostConstruct
public void init() { System.out.println("Bean initialized"); }

@PreDestroy

Definition: Marks a method to be called before the bean is destroyed.

Usage: Used for cleanup logic before the bean is removed.

Example:

@PreDestroy
public void destroy() { System.out.println("Cleaning up"); }



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:

@RequestMapping("/api")
public class ApiController { @RequestMapping("/status") public String status() { return "OK"; } }

@GetMapping, @PostMapping, @PutMapping, @PatchMapping, @DeleteMapping

Definition: Shorthand for @RequestMapping with specific HTTP methods.

Usage: Used to handle RESTful requests.

Example:

@GetMapping("/users")
public List<User> getUsers() { return userService.getAll(); }

@RequestParam

Definition: Binds a request parameter to a method argument.

Usage: Used to extract query parameters from a request.

Example:

@GetMapping("/greet")
public String greet(@RequestParam String name) { return "Hello, " + name; }

@PathVariable

Definition: Binds a URI path variable to a method parameter.

Usage: Used to extract dynamic segments from the URL.

Example:

@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id) { return userService.findById(id); }

@RequestBody

Definition: Binds the body of an HTTP request to an object.

Usage: Used for handling JSON/XML payloads.

Example:

@PostMapping("/users")
public void createUser(@RequestBody User user) { userService.save(user); }

@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:

@ResponseBody
@GetMapping("/ping") public String ping() { return "pong"; }

@RestController

Definition: A shortcut for @Controller + @ResponseBody.

Usage: Used to create RESTful web services.

Example:

@RestController
public class UserController { @GetMapping("/users") public List<User> allUsers() { return userService.getAll(); } }

@RequestHeader

Definition: Binds a method parameter to an HTTP header.

Usage: Used to access request headers.

Example:

@GetMapping("/user-agent")
public String getUserAgent(@RequestHeader("User-Agent") String userAgent) { return userAgent; }

@CookieValue

Definition: Binds a method parameter to a cookie value.

Usage:
Used to read cookies.

Example:

@GetMapping("/session")
public String session(@CookieValue("sessionId") String sessionId) { return "Session: " + sessionId; }

@SessionAttribute

Definition: Binds a method parameter to a session attribute.

Usage: Used to retrieve session-scoped data.

Example:

@GetMapping("/profile")
public String profile(@SessionAttribute("user") User user) { return user.getName(); }

@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:

@ModelAttribute("user")
public User initUser() { return new User(); }

@InitBinder

Definition: Customizes data binding for request parameters.

Usage: Used to register custom editors or formatters.

Example:

@InitBinder
public void initBinder(WebDataBinder binder) { binder.setDisallowedFields("id"); }

@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

Definition: Composite annotation combining @Configuration, @EnableAutoConfiguration, and @ComponentScan.

Usage: Entry point for a Spring Boot application.

Example:

@SpringBootApplication
public class MyApp { public static void main(String[] args) { SpringApplication.run(MyApp.class, args); } }

@EnableAutoConfiguration

Definition: Tells Spring Boot to automatically configure beans based on classpath settings.

Usage: Often included in @SpringBootApplication, but can be used separately if needed.

Example:

@EnableAutoConfiguration public class AppConfig { }

@ComponentScan

Definition: Specifies base packages to scan for annotated components.

Usage: Used when components are in different packages not scanned by default.

Example:

@ComponentScan(basePackages = "com.example.services") public class AppConfig { }

@ConfigurationProperties

Definition: Maps properties defined in application.properties or application.yml to a Java class.

Usage: Used to bind configuration properties to POJOs.

Example:

@Component
@ConfigurationProperties(prefix = "app") public class AppProperties { private String name; private int timeout; // getters and setters }

@SpringBootTest

Definition: Loads the full application context for integration tests.

Usage: Used for writing Spring Boot integration or context tests.

Example:

@SpringBootTest public class ApplicationTests { @Test public void contextLoads() { } }

@TestConfiguration

Definition: Defines additional beans or config only used in tests.

Usage: Useful to mock or replace certain beans during testing.

Example:

@TestConfiguration
public class TestBeansConfig { @Bean public MyService testService() { return new MyServiceMock(); } }

@RequestScope, @SessionScope, @ApplicationScope

Definition: Declares bean scopes tied to HTTP request, session, or application context respectively.

Usage: Used when different lifecycle control is needed for a bean.

Example:

@Component
@RequestScope public class RequestLogger { public void log() { System.out.println("Request-scoped logger"); } }



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:

@Entity
public class User { @Id private Long id; private String name; }

@Table

Definition: Specifies the table name mapped to the entity.

Usage: Used to customize the table name or schema.

Example:

@Entity
@Table(name = "users") public class User { ... }

@Id

Definition: Marks a field as the primary key.

Usage: Mandatory for each entity to uniquely identify records.

Example:

@Id
@GeneratedValue private Long id;

@GeneratedValue

Definition: Specifies how the primary key should be generated.

Usage: Used in combination with @Id.

Example:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;

@Column

Definition: Customizes mapping of a field to a column.

Usage: Used to define column properties like name, length, nullable, etc.

Example:

@Column(name = "username", nullable = false, length = 50)
private String name;

@Transient

Definition: Prevents a field from being persisted to the database.

Usage: Useful for temporary or calculated fields.

Example:

@Transient
private String sessionToken;

@Lob

Definition: Maps a large object (CLOB/BLOB) to the database.

Usage: Used for large text or binary content.

Example:

@Lob
private String longDescription;

@Temporal

Definition: Specifies the format for java.util.Date persistence.

Usage: Used with legacy Date or Calendar objects.

Example:

@Temporal(TemporalType.DATE)
private Date birthDate;

@OneToOne, @OneToMany, @ManyToOne, @ManyToMany

Definition: Define relationships between JPA entities.

Usage: Used to model associations in object-relational mapping.

Example:

@OneToMany(mappedBy = "user")
private List<Order> orders;

@JoinColumn

Definition: Specifies the foreign key column for relationships.

Usage: Used with associations to define how tables are joined.

Example:

@ManyToOne
@JoinColumn(name = "user_id") private User user;

@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:

@MappedSuperclass
public abstract class Auditable { private LocalDateTime createdAt; }

@Embeddable, and @Embedded

Definition: Used to create component objects inside entities (value objects).

Usage: Used to group fields into reusable embeddable objects.

Example:

@Embeddable
public class Address { private String city; private String zip; } @Embedded private Address address;

@Query

Definition: Defines custom JPQL or native SQL queries on a repository method.

Usage: Used when the default query derivation is not enough.

Example:

@Query("SELECT u FROM User u WHERE u.email = ?1")
User findByEmail(String email);

@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:

@Modifying
@Query("DELETE FROM User u WHERE u.lastLogin < :cutoff") void deleteInactiveUsers(@Param("cutoff") LocalDate date);

@Param

Definition: Maps method parameters to query named parameters.

Usage: Used inside @Query statements.

Example:

@Query("SELECT u FROM User u WHERE u.name = :name")
User findByName(@Param("name") String name);

@EnableJpaRepositories

Definition: Enables JPA repositories by scanning packages.

Usage: Placed on a configuration class to activate Spring Data JPA support.

Example:

@EnableJpaRepositories(basePackages = "com.example.repo")
public class JpaConfig { }

@RepositoryRestResource

Definition: Exposes a Spring Data JPA repository as a REST endpoint.

Usage: Used in Spring Data REST projects.

Example:

@RepositoryRestResource(path = "users")
public interface UserRepository extends JpaRepository<User, Long> { }

@Transactional

Definition: Wraps a method or class with transaction boundaries.

Usage: Used for methods interacting with the database.

Example:

@Transactional
public void saveUser(User user) { userRepository.save(user); }

@EnableTransactionManagement

Definition: Enables support for the @Transactional annotation.

Usage: Add to configuration class to enable declarative transactions.

Example:

@Configuration
@EnableTransactionManagement public class TransactionConfig { }


@Lock

Definition: Applies a locking strategy (PESSIMISTIC or OPTIMISTIC) on a query.

Usage: Used for concurrency control.

Example:

@Lock(LockModeType.PESSIMISTIC_WRITE) @Query("SELECT u FROM User u WHERE u.id = :id") User findByIdForUpdate(@Param("id") Long id);

Spring-Specific? No (JPA standard)



5. Spring Caching Annotations


@EnableCaching

Definition: Enables Spring’s cache abstraction.

Usage: Added to configuration class to allow caching annotations.

Example:

@Configuration
@EnableCaching public class CacheConfig { }

@Cacheable

Definition: Caches the result of a method call.

Usage: Used when repeated calls with the same parameters can return cached result.

Example:

@Cacheable("users")
public User getUserById(Long id) { return userRepository.findById(id).orElse(null); }

@CachePut

Definition: Updates the cache with the latest method result.

Usage: Used to force cache update when a method is invoked.

Example:

@CachePut("users")
public User updateUser(User user) { return userRepository.save(user); }

@CacheEvict

Definition: Removes specific entries from the cache.

Usage: Used when data is deleted or modified and must be removed from the cache.

Example:

@CacheEvict(value = "users", key = "#id")
public void deleteUser(Long id) { userRepository.deleteById(id); }

@Caching

Definition: Combines multiple caching annotations on a single method.

Usage: Useful when a method needs a combination of @CachePut, @CacheEvict, etc.

Example:

@Caching(
evict = { @CacheEvict("users") }, put = { @CachePut("logs") } ) public void updateAndLog(User user) { // logic }



6. Spring AOP Annotations


@Aspect

Definition: Marks a class as containing cross-cutting concerns (like logging, security, etc.).

Usage: Used with @Before, @After, etc. to define advice.

Example:

@Aspect
public class LoggingAspect { @Before("execution(* com.example.service.*.*(..))") public void logBefore() { System.out.println("Method called"); } }

@Before, @After, @AfterReturning, @AfterThrowing, @Around

Definition: Define when a method (advice) should be executed in relation to a join point (target method).

Usage: Used for cross-cutting concerns such as logging, security, etc.

Example:

@Around("execution(* com.example..*(..))")
public Object logExecution(ProceedingJoinPoint joinPoint) throws Throwable { System.out.println("Before execution"); Object result = joinPoint.proceed(); System.out.println("After execution"); return result; }

@Pointcut

Definition: Declares reusable pointcut expressions.

Usage: Used to centralize expression definitions for @Before, @Around, etc.

Example:

@Pointcut("execution(* com.example.service.*.*(..))")
public void serviceMethods() { }



7. Spring Scheduling & Async Execution Annotations


@EnableScheduling

Definition: Enables scheduled task execution.

Usage: Added to config class to allow @Scheduled annotations.

Example:

@Configuration
@EnableScheduling public class SchedulingConfig { }

@Scheduled

Definition: Schedules a method to be invoked at fixed intervals.

Usage: Used for periodic jobs.

Example:

@Scheduled(fixedRate = 60000)
public void runJob() { System.out.println("Running every 60 seconds"); }

@EnableAsync

Definition: Enables support for asynchronous method execution.

Usage: Added to config class to allow @Async methods.

Example:

@Configuration
@EnableAsync public class AsyncConfig { }

@Async

Definition: Indicates that a method should be executed asynchronously.

Usage: Used to execute a method in a separate thread.

Example:

@Async
public void sendNotificationEmail() { // send email in background }



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:

@Secured("ROLE_ADMIN") public void deleteUser(Long id) { // only accessible to admin users }

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:

@RolesAllowed("ROLE_USER") public String viewProfile() { return "profile page"; }

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:

@PreAuthorize("hasRole('ADMIN')") public void createProject(Project p) { // only if caller has ADMIN role }

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:

@PostAuthorize("returnObject.owner == authentication.name") public Document getDocument(Long id) { return documentRepository.findById(id).orElse(null); }

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:

@PreFilter("filterObject.owner == authentication.name") public void deleteDocuments(List<Document> docs) { // only deletes docs owned by the current user }

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:

@PostFilter("filterObject.owner == authentication.name") public List<Document> getDocuments() { return documentRepository.findAll(); }

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:

@Configuration @EnableGlobalMethodSecurity( securedEnabled = true, prePostEnabled = true, jsr250Enabled = true ) public class MethodSecurityConfig { }

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):

@PostMapping("/users") public ResponseEntity<String> createUser(@Valid @RequestBody User user) { return ResponseEntity.ok("User is valid!"); }

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):

@Validated @Service public class UserService { public void processUser(@Validated(OnCreate.class) User user) { // validation applies only for the OnCreate group } }

Spring-Specific? Yes


@NotNull

Definition: Validates that the annotated value is not null.

Usage: Used on fields where null values are not acceptable.

Example:

@NotNull(message = "Username must not be null") private String username;

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:

@NotBlank(message = "Name is required") private String name;

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:

@NotEmpty private List<String> roles;

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:

@Size(min = 6, max = 20) private String password;

Spring-Specific? No


@Email

Definition: Validates that a string is a well-formed email address.

Usage: Used for email field validation.

Example:

@Email private String email;

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:

@Min(18) @Max(99) private int age;

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:

@Pattern(regexp = "^[A-Z][a-z]+$") private String firstName;

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:

@AssertTrue private boolean termsAccepted;

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:

@Past private LocalDate birthDate; @Future private LocalDate subscriptionEndDate;

Spring-Specific? No


@Constraint

Definition: Marks an annotation as a custom validation constraint.

Usage: Used to create custom validators (e.g., @ValidPhoneNumber, @ValidCurrency).

Example:

@Constraint(validatedBy = MyCustomValidator.class) @Target({ ElementType.FIELD }) @Retention(RetentionPolicy.RUNTIME) public @interface ValidCountry { String message() default "Invalid country"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }

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:

@Profile("dev")
@Component public class DevDataSourceConfig { @Bean public DataSource dataSource() { return new H2DataSource(); } }

In application.properties:

spring.profiles.active=dev

@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:

@Configuration public class AppConfig { @Bean @Conditional(MyCondition.class) public MyService myService() { return new MyService(); } }

Custom condition:

public class MyCondition implements Condition { public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { return context.getEnvironment().containsProperty("app.enabled"); } }

@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:

@Component @ConditionalOnProperty(name = "feature.sms.enabled", havingValue = "true") public class SmsService { // Loaded only if feature.sms.enabled=true }

In application.properties:

feature.sms.enabled=true

@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:

@Configuration public class DefaultServiceConfig { @Bean @ConditionalOnMissingBean(MyService.class) public MyService defaultMyService() { return new DefaultMyService(); } }

@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:

@Component @ConditionalOnBean(EmailService.class) public class NotificationService { // Loaded only if EmailService is present }

@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:

@Configuration @ConditionalOnClass(name = "com.fasterxml.jackson.databind.ObjectMapper") public class JsonConfig { @Bean public ObjectMapper objectMapper() { return new ObjectMapper(); } }

@ConditionalOnExpression (Spring Boot)

Definition: Registers a bean conditionally based on a SpEL (Spring Expression Language) expression.

Usage: Used for flexible configuration using expressions.

Example:

@Bean @ConditionalOnExpression("${feature.toggle:true} == true") public FeatureService featureService() { return new FeatureService(); }

@ActiveProfiles

Definition: Specifies active Spring profiles when running a test.

Usage: Used in Spring Boot tests to simulate different runtime environments.

Example:

@SpringBootTest @ActiveProfiles("test") public class UserServiceTest { @Autowired UserService userService; }

@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):

spring: profiles: group: prod: - prod-db - prod-security

Then in properties:

spring.profiles.active=prod

(All profiles in the group will be activated.)



11. Spring Configuration Import & Dependencies Annotations


@Import

Definition: Imports one or more @Configuration or component classes into another configuration class,

allowing them to be registered as beans in the application context.

Usage: Used to modularize and reuse configuration classes without scanning them explicitly.

Example:

@Configuration
@Import({SecurityConfig.class, DataSourceConfig.class})
public class MainConfig {
// Main configuration class that includes other configs
}

This allows SecurityConfig and DataSourceConfig to be loaded and processed as part of MainConfig.


@ImportResource

@Configuration
@ImportResource("classpath:applicationContext.xml")

public class AppConfig {
// Loads beans defined in applicationContext.xml
}

Definition: Imports Spring configuration from an external XML file into a Java-based configuration class.

Usage: Used when you want to combine legacy XML-based Spring configuration with newer Java-based configuration.

Example:

This helps during transitional phases where not all configurations are moved to Java classes.


@DependsOn

Definition: Indicates that a bean depends on the initialization of one or more other beans.

Spring ensures the dependent beans are created first.

Usage: Used when a bean must be initialized only after another bean is fully initialized,

such as ordering system components or initializing shared resources.

Example:

@Component
@DependsOn("dataSourceInitializer")
public class UserRepository {
// This bean is created only after dataSourceInitializer is initialized
}

Spring uses this annotation to determine bean creation order during application context initialization.


@PropertySource

Definition: Loads property files into the Spring Environment.

Usage: Used to load .properties files manually when they aren’t located in default locations like application.properties.

Example:

@Configuration @PropertySource("classpath:external-config.properties") public class PropertyConfig { }

This allows values from external-config.properties to be injected via @Value or accessed from the environment.


@PropertySources

Definition: Container annotation for defining multiple @PropertySource annotations.

Usage: Used to load multiple property files in the same configuration class.

Example:

@Configuration @PropertySources({ @PropertySource("classpath:db.properties"), @PropertySource("classpath:app.properties") }) public class MultiPropertyConfig { }

@ConfigurationProperties

Definition: Binds external configuration properties (from .properties or .yml) to Java beans.

Usage: Used to map groups of related configuration values to a POJO.

Example:

@Component @ConfigurationProperties(prefix = "app") public class AppSettings { private String name; private int timeout; // getters and setters }

In application.properties:

app.name=MyApp app.timeout=60

@ConfigurationPropertiesScan(Spring Boot 2.2+)

Definition: Scans packages for @ConfigurationProperties classes automatically, eliminating the need for explicit @Component.

Usage: Used in combination with @SpringBootApplication or @Configuration.

Example:

@ConfigurationPropertiesScan("com.example.config") @SpringBootApplication public class MyApplication { }

@EnableConfigurationProperties

Definition: Registers @ConfigurationProperties beans without requiring @Component.

Usage: Used in non-component classes like @Configuration.

Example:

@Configuration @EnableConfigurationProperties(AppSettings.class) public class ConfigClass { }

@ImportRuntimeHints(Spring Native)

Definition: Provides runtime hints (like reflection or resource access) needed during ahead-of-time (AOT) compilation in Spring Native/GraalVM.

Usage: Used when running Spring Boot applications as native images.

Example:

@ImportRuntimeHints(MyHints.class) @Configuration public class NativeConfig { }

Where MyHints is a class implementing RuntimeHintsRegistrar.



12. Bean Lifecycle & Injection Enhancements Annotations


@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:

@Component public class CacheLoader { @PostConstruct public void init() { System.out.println("Loading cache after bean creation"); } }

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:

@Component public class FileWriterBean { @PreDestroy public void closeFile() { System.out.println("File closed during bean destruction"); } }

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:

@Component public class EmployeeService { @Required public void setRepository(EmployeeRepository repo) { this.repo = repo; } }

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:

@Component public class ReportManager { @Lookup public ReportGenerator getReportGenerator() { // Spring overrides this method with a proxy return null; } }

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:

@Component public class BillingService { @Inject private PaymentGateway paymentGateway; }

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:

@Component public class EmailService { @Resource(name = "smtpSender") private MailSender mailSender; }

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