OPK
OPK

Reputation: 4180

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?

Upvotes: 4

Views: 1625

Answers (3)

Avi
Avi

Reputation: 21760

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;
}

Upvotes: 7

seanhodges
seanhodges

Reputation: 17524

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.

Upvotes: 0

Sarath Chandra
Sarath Chandra

Reputation: 1878

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.

Upvotes: 0

Related Questions