It is mainly meant for solving ambiguity when performing an auto-scan and using @Autowired
. I gave a thorough answer explaining about @Autowired
in this answer which also explains about the need to name the beans.
Let's assume we have 2 classes that implement CustomerRepository
:
@Repository
public class MyCustomerRepositoryImpl implements CustomerRepository {
}
@Repository
public class OtherCustomerRepositoryImpl implements CustomerRepository {
}
Let's now assume we have a class that uses @Autowired
to inject a CustomerRepository
:
public class SomeClass {
@Autowired
private CustomerRepository customerRepository;
}
When performing an auto-scan, you need to have a way to differentiate between them. Otherwise Spring would throw an exception saying that it can't tell which of the beans should be injected.
So we can now add a logical name to each implementation:
@Repository("myRepository")
public class MyCustomerRepositoryImpl implements CustomerRepository {
}
@Repository("otherRepository")
public class OtherCustomerRepositoryImpl implements CustomerRepository {
}
And now you can help Spring solve the ambiguity as follows:
public class SomeClass {
@Autowired
@Qualifier("myRepository")
private CustomerRepository customerRepository;
}