@Qualifier and @Primary are Spring annotations used to resolve bean injection conflicts when multiple beans of the same type exist. @Qualifier explicitly specifies which bean should be injected, while @Primary designates a default bean that Spring should choose automatically. Similarly, @Component and @Service are stereotype annotations used to create Spring-managed beans, but @Service specifically represents business logic components.
Key Points: • @Qualifier provides precise bean selection, whereas @Primary defines the default bean for dependency injection. • @Qualifier is used at injection points, while @Primary is applied to the bean definition itself. • @Service is a specialized version of @Component intended for service-layer classes, although both create Spring beans.
Difference Between @Qualifier and @Primary:
@Primary: • Marks a bean as the default choice. • Used when multiple beans of the same type exist. • Spring automatically injects the primary bean unless another bean is explicitly specified.
@Qualifier: • Selects a specific bean by name. • Overrides @Primary when used. • Provides fine-grained control over dependency injection.
Code Example:
@Component
@Primary
class MySqlDatabase
implements Database {
}
@Component
class OracleDatabase
implements Database {
}
@Service
class UserService {
@Autowired
@Qualifier("oracleDatabase")
private Database database;
}In this example: • MySqlDatabase is the default bean. • @Qualifier forces Spring to inject OracleDatabase instead.
Where Are These Used? • Applications with multiple implementations of the same interface. • Payment gateways (Credit Card, PayPal, UPI). • Multiple database providers. • Different notification services (Email, SMS, Push).
Difference Between @Component and @Service:
@Component: • Generic stereotype annotation. • Used for utility classes, helpers, and generic Spring-managed beans.
@Service: • Specialized form of @Component. • Used specifically for business logic and service-layer classes.
Hierarchy:
@Component ↑
@Repository
@Service
@ControllerExample:
@Component
public class FileUtil {
}
@Service
public class PaymentService {
}Are @Component and @Service Interchangeable?
Technically: • Yes, both register Spring beans. • Both are detected during component scanning.
Practically: • No, use @Service for business logic. • Use @Component for generic supporting classes. • Improves readability and application architecture.
Example: In an e-commerce application: • PaymentService → @Service • EmailUtil → @Component
Interview Tip: A concise interview answer is: @Primary defines the default bean to inject when multiple beans of the same type exist, while @Qualifier explicitly selects a particular bean and overrides @Primary. @Component is a generic Spring stereotype, whereas @Service is a specialized @Component used for business logic. Although @Component and @Service are technically interchangeable, using @Service improves code clarity and architectural consistency.