Spring Boot Interview Questions
Spring Boot
Java
BackendWeb DevelopmentQuestion 9
Explain the difference between @Component
, @Service
, and @Repository
annotations.
Answer:
In Spring, the @Component
, @Service
, and @Repository
annotations are all specializations of the @Component
annotation. They are used to indicate that a class is a Spring-managed component and to automatically register beans in the Spring application context. Each of these annotations serves a slightly different purpose and is intended to be used in specific layers of an application.
@Component
- General Purpose:
@Component
is a generic stereotype annotation indicating that the annotated class is a Spring-managed component. It can be used for any Spring bean, and it is the most general of the three annotations. - Use Case: Typically used for classes that do not fall into the
Service
orRepository
categories, such as utility classes, helper classes, or other components. - Example:
import org.springframework.stereotype.Component; @Component public class MyComponent { public void performTask() { // Business logic } }
@Service
- Service Layer:
@Service
is a specialization of@Component
that is used to indicate that a class defines a business service. It is used to mark the service layer of an application. - Semantic Clarity: Using
@Service
provides better semantic clarity and conveys the intent of the class, which is to encapsulate business logic and service-related functionality. - Use Case: Typically used for service classes that contain business logic or call methods from multiple repositories.
- Example:
import org.springframework.stereotype.Service; @Service public class MyService { public void executeService() { // Business logic } }
@Repository
- Data Access Layer:
@Repository
is a specialization of@Component
that indicates that the annotated class is a repository, which is responsible for encapsulating storage, retrieval, and search behavior. It is used to mark the data access layer. - Persistence Exception Translation:
@Repository
has an additional feature for automatic translation of persistence-related exceptions into SpringβsDataAccessException
, which helps in handling database exceptions in a consistent way. - Use Case: Typically used for DAO (Data Access Object) classes that interact with the database.
- Example:
import org.springframework.stereotype.Repository; @Repository public class MyRepository { public void saveData() { // Data access logic } }
Summary of Differences
-
@Component:
- General-purpose annotation.
- Indicates that the class is a Spring-managed component.
- Can be used for any Spring bean.
- Suitable for utility or helper classes.
-
@Service:
- Specialized for the service layer.
- Indicates that the class provides business services.
- Provides semantic clarity for business logic classes.
- Suitable for classes containing business logic or service-related functionality.
-
@Repository:
- Specialized for the data access layer.
- Indicates that the class is a repository or DAO.
- Includes additional persistence exception translation.
- Suitable for classes that interact with the database.
Practical Example
Consider a simple application with a service that retrieves and processes data from a database. Hereβs how you might use these annotations:
Repository Layer
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
// Custom query methods (if any)
}
Service Layer
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
private final UserRepository userRepository;
@Autowired
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public User getUserById(Long id) {
return userRepository.findById(id).orElse(null);
}
// Other business logic methods
}
Component Layer
import org.springframework.stereotype.Component;
@Component
public class UserValidator {
public boolean validateUser(User user) {
// Validation logic
return user != null && user.getName() != null;
}
}
Conclusion
- @Component: Use for general-purpose Spring beans that donβt fit into the other categories.
- @Service: Use for classes that provide business logic and services.
- @Repository: Use for classes that handle data access and interact with the database, benefiting from exception translation.
By using these annotations appropriately, you can make your Spring application more organized, with clear separation of concerns and well-defined layers.