4

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?

OPK
  • 4,120
  • 6
  • 36
  • 66

3 Answers3

7

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;
}
Community
  • 1
  • 1
Avi
  • 21,182
  • 26
  • 82
  • 121
0

It helps to convert the entity into a Spring bean, if autodetected.

From the official doc here:-

The value may indicate a suggestion for a logical component name, to be turned into a Spring bean in case of an autodetected component.

Sarath Chandra
  • 1,850
  • 19
  • 40
0

The AnnotationBeanNameGenerator is responsible for picking a name for your beans. If you specify a name you can use a different convention for your bean names than what would otherwise be generated based on the class name.

Auto-generated bean names are not fool proof; two classes with the same name can cause a duplicate bean definition, as can two classes inheriting the same interface.

The use of explicit names also ensures that code refactoring does not implicitly break the bean wiring.

seanhodges
  • 17,426
  • 15
  • 71
  • 93