Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a reason that we give spring annotation a name?

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?

like image 852
OPK Avatar asked Mar 15 '23 07:03

OPK


1 Answers

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;
}
like image 187
Avi Avatar answered Mar 26 '23 21:03

Avi