I noticed when using annotation for spring or spring mvc, some programmers give the annotation a name along with it. For example:
@Repository("customerRepository")
public class CustomerRepositoryImpl implements CustomerRepository{
}
I believe the class functioning the same without giving the @Repository
a name. Would there be a situation that name the annotation useful?
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With