In Spring Framework, both Primary and Qualifier annotations are used for dependency injection, but they serve different purposes.
Primary Annotation: The Primary annotation is used to specify the primary bean to be used in case of multiple beans of the same type. When multiple beans of the same type are present in the application context and no qualifier is provided, the bean marked with the Primary annotation will be chosen as the default bean.
Qualifier Annotation: The Qualifier annotation is used to specify which bean to use when there are multiple beans of the same type in the application context. It allows you to differentiate between beans of the same type by assigning a unique identifier to each bean.
For example, let's say you have multiple implementations of the UserDao interface. You can use the Qualifier annotation to specify which implementation to use in a particular context.
Example:
public interface UserDao {
// ...
}
@Component
@Qualifier("userDaoImplOne")
public class UserDaoImplOne implements UserDao {
// ...
}
@Component
@Qualifier("userDaoImplTwo")
public class UserDaoImplTwo implements UserDao {
// ...
}
@Service
public class UserService {
@Autowired
@Qualifier("userDaoImplTwo")
private UserDao userDao;
// ...
}
In the above example, we have defined two implementations of UserDao with the Qualifier annotation to differentiate between them. In the UserService class, we use the Qualifier annotation to specify which UserDao implementation to use for dependency injection.
Overall, Primary and Qualifier annotations are both used for dependency injection in Spring Framework, but they serve different purposes. Primary is used to specify the default bean in case of multiple beans of the same type, while Qualifier is used to specify which bean to use in a particular context when there are multiple beans of the same type.