Here is a comprehensive set of 15 interview questions and answers on Spring & Spring Boot annotations, including a detailed breakdown of @Component vs @Repository at the repository level.
Q1: What is the difference between @Component and @Repository when used at the persistence/repository layer?¶
Answer: While both annotations register a class as a Spring-managed bean in the IoC container during component scanning, using @Repository instead of @Component at the data access level brings important technical advantages:
-
Exception Translation (Persistence Level):
@Repositoryautomatically enables Spring'sPersistenceExceptionTranslationPostProcessor. It intercepts low-level database exceptions (such as JDBCSQLException, Hibernate exceptions, or JPA persistence exceptions) and automatically translates them into Spring’s uniform, uncheckedDataAccessExceptionhierarchy. Plain@Componentdoes not provide this exception translation behavior. -
Architectural Semantics:
@Repositoryexplicitly marks the class as a Data Access Object (DAO) or persistence component , clearly declaring its role in a layered architecture. -
AOP Interception: Aspects or pointcuts targeted specifically at the database/DAO layer (such as custom auditing or query logging) typically target classes annotated with
@Repository.
Q2: What is the difference between @Controller and @RestController?¶
Answer: * @Controller: Designed for traditional Spring MVC web applications. Handler methods typically return a String representing a view name (like HTML or JSP). If a @Controller method needs to return raw data (e.g., JSON), it must explicitly be annotated with @ResponseBody.
@RestController: Designed specifically for RESTful Web APIs. It is a convenience composite annotation that combines@Controllerand@ResponseBody. Every handler method inside a@RestControllerautomatically serializes its return value directly into the HTTP response body (JSON/XML).
Q3: When should you use @Component versus @Bean?¶
Answer: * @Component: Used for class-level component auto-detection via classpath scanning. It is applied directly to custom Java source code classes that you own and can modify.
@Bean: Used for method-level declarations inside a@Configurationclass. It is ideal when configuring third-party library classes or custom instances where you do not own or cannot edit the source code to add@Component.
Q4: What is the difference between field injection using @Autowired and constructor injection? Why is constructor injection preferred?¶
Answer: * Field Injection (@Autowired on field): Uses reflection directly on private fields to inject dependencies. It can lead to NullPointerExceptions in unit tests if Spring is not running.
- Constructor Injection: Dependencies are passed explicitly via the class constructor.
Why Constructor Injection is Preferred: 1. Immutability: Dependencies can be declared as final fields.
-
Ease of Unit Testing: You can easily pass mock objects via the constructor without needing reflection or Spring's container.
-
No
@Autowiredrequirement: Since Spring 4.3, if a class has only one constructor, Spring automatically autowires dependencies without needing explicit@Autowiredannotations.
Q5: How do @Qualifier and @Primary resolve dependency injection ambiguities?¶
Answer: When multiple beans implementation of the same interface exist in the container:
-
@Primary: Sets a global default preference at the bean definition level. When autowiring without extra qualification, Spring will select the@Primarybean. -
@Qualifier: Used at the injection point (@Autowired) to specify the exact name of the target bean to inject.@Qualifieroverrides@Primarywhen explicit target bean selection is required.
Q6: What is the difference between @PathVariable and @RequestParam?¶
Answer: * @PathVariable: Extracts parameters embedded directly within the URI path template (e.g., /users/{userId} where URI is /users/101).
@RequestParam: Extracts query parameters or form data appended to the URL string (e.g.,/users?userId=101).
Q7: What does @SpringBootApplication do under the hood?¶
Answer: @SpringBootApplication is a meta-annotation that encapsulates three core Spring annotations:
-
@SpringBootConfiguration(or@Configuration): Enables Java-based bean configuration. -
@EnableAutoConfiguration: Triggers Spring Boot's auto-configuration engine to configure beans automatically based on the dependencies found on the classpath. -
@ComponentScan: Enables component scanning for stereotype annotations (@Component,@Service,@Repository,@RestController) starting from the package containing the main application class and its sub-packages.
Q8: How does @Transactional work in Spring, and what are its common failure scenarios?¶
Answer: @Transactional uses Aspect-Oriented Programming (AOP) to create dynamic proxies around Spring beans to manage database transaction boundaries (begin, commit, rollback).
Common Failure Scenarios:
-
Self-Invocation: Calling a
@Transactionalmethod from another method inside the same class bypasses the Spring proxy, causing the transaction advice to be skipped. -
Unchecked vs Checked Exceptions: By default, transactions only roll back on unchecked exceptions (
RuntimeExceptionandError). To handle checked exceptions,rollbackFor = Exception.classmust be specified. -
Non-Public Methods:
@Transactionalvisibility rules state that proxying applies topublicmethods.
Q9: How do @ControllerAdvice and @ExceptionHandler enable global exception handling in Spring Boot?¶
Answer: * @ExceptionHandler: Used inside a controller class to define custom exception handler methods for specific exceptions thrown within that controller.
@ControllerAdvice(or@RestControllerAdvice): Acts as a global interceptor across all controllers in the application. By placing@ExceptionHandlermethods inside a@ControllerAdviceclass, exception handling is centralized, eliminating duplicate try-catch blocks across controllers.
Q10: What are @PostConstruct and @PreDestroy used for in bean lifecycle management?¶
Answer: * @PostConstruct: Marks a method to be executed immediately after Spring creates the bean and completes dependency injection. It is used for initialization tasks.
@PreDestroy: Marks a method to be executed right before the bean is destroyed by the container. It is used for cleanup operations like closing DB connections or freeing resources.
Q11: How does Component Scanning (@ComponentScan) work, and what is its default path constraint?¶
Answer: @ComponentScan instructs Spring to scan specified packages for classes annotated with @Component, @Service, @Repository, or @Controller to register them as managed beans.
-
Default Constraint: By default, Spring Boot scans the package containing the main class annotated with
@SpringBootApplicationand all of its sub-packages. -
Key Pitfall: If a component class is placed outside or above the main application package, it will not be detected during component scanning unless explicitly defined using
@ComponentScan(basePackages = "...").
Q12: What happens if a Spring Bean requires a constructor argument that Spring cannot resolve during startup?¶
Answer: If a class registered as a Spring Bean has a parameterized constructor, Spring attempts to resolve all constructor arguments from its ApplicationContext.
If an argument (such as a plain String, integer, or unregistered class) cannot be resolved as a managed bean in the container, application startup fails with a BeanCreationException / dependency resolution failure. Missing custom types must be explicitly declared as beans (via @Component or @Bean) or injected via @Value.
Q13: What is the difference between @Value and @ConfigurationProperties for reading external configurations?¶
Answer: * @Value: Reads property values individually field-by-field using expression syntax (e.g., @Value("${server.port}")). Useful for simple, single-property injections.
@ConfigurationProperties: Binds structured, hierarchical configuration properties (e.g., fromapplication.yml) to a strongly-typed Java class. Supports relaxed binding, type validation, and nested properties.
Q14: How does @EnableAutoConfiguration work in Spring Boot?¶
Answer: @EnableAutoConfiguration scans the application's classpath for included library dependencies (e.g., spring-boot-starter-web, spring-boot-starter-data-jpa). Using conditional annotations like @ConditionalOnClass or @ConditionalOnMissingBean, Spring Boot automatically configures default infrastructure beans (such as an embedded Tomcat server or DataSource) without requiring manual XML/Java configuration.
Q15: How do @EnableAsync and @Async execute background tasks in Spring?¶
Answer: * @EnableAsync: Enables Spring's asynchronous method execution capabilities across the application.
@Async: Placed on a specific method to execute it in a separate thread pool asynchronously. The caller method returns immediately without waiting for the completion of the@Asyncmethod execution.
@Component vs Controller, service and repository¶
This is a very common Spring interview question.
Question
What happens if we use @Component instead of @Repository on the repository layer?
Short Answer
The application will still work because @Repository is a specialized version of @Component.
However, using @Repository is the recommended approach because it provides additional functionality that @Component does not.
Why does it still work?
@Repository is itself annotated with @Component.
Its definition is conceptually similar to:
@Component
public @interface Repository {
}
This means that when Spring performs component scanning, both annotations register the class as a Spring Bean.
So this works:
@Component
public class EmployeeRepository {
}
And this also works:
@Repository
public class EmployeeRepository {
}
Both become Spring Beans.
Then why use @Repository?
Because it has an additional feature called Exception Translation.
Suppose you're using JDBC, Hibernate, or JPA.
A database throws this exception:
SQLException
Spring automatically converts it into one of its own unchecked exceptions like:
DataAccessException
This automatic conversion only happens for classes marked with:
@Repository
Example
Without @Repository
@Component
public class EmployeeRepository {
}
Database may throw
SQLException
You'll have to handle vendor-specific exceptions yourself.
With @Repository
@Repository
public class EmployeeRepository {
}
Spring converts exceptions like
SQLException
into
DataAccessException
which is database-independent.
Advantages of @Repository
✔ Registers the class as a Spring Bean.
✔ Indicates that the class belongs to the persistence layer.
✔ Enables automatic persistence exception translation.
✔ Makes the code more readable and easier to maintain.
Difference
Feature @Component @Repository
Spring Bean ✅ ✅
Component Scanning ✅ ✅
Generic Annotation ✅ ❌
Persistence Layer Semantics ❌ ✅
Exception Translation ❌ ✅
Recommended for DAO Layer ❌ ✅
Interview Answer (2--3 lines)
@Repository is a specialized form of @Component, so using @Component at the repository layer will still register the class as a Spring Bean. However, @Repository is preferred because it clearly identifies the persistence layer and enables Spring's automatic translation of database-specific exceptions into the DataAccessException hierarchy.
Follow-up Interview Question
Q: Can I replace @Service, @Repository, and @Controller with @Component?
Answer:
Yes, technically you can because all three are specialized stereotype annotations built on top of @Component. The application will still run. However, it is not recommended because each annotation conveys the class's role in the application, and some provide additional behavior:
@Service → Marks business logic (primarily semantic).
@Repository → Marks the persistence layer and enables exception translation.
@Controller → Marks MVC controllers that handle web requests.
@RestController → Combines @Controller and @ResponseBody to simplify REST API development.
Using the appropriate stereotype improves readability, maintainability, and, in the case of @Repository, provides extra functionality.