Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Both @Component and @Named for the same bean class

Does a class which will act as a bean in a Spring application require both @Component and @Named at the same time?

What is the significance if both are used so?

I tried searching the net as well as saw the standard documentation of these annotations and found them a bit confusing.

Finally which name is taken by the application if the @Named annotation does not specify any name for the bean?

like image 974
TechSpellBound Avatar asked Apr 17 '12 10:04

TechSpellBound


People also ask

Is @bean and @component same?

@Component is a class-level annotation, but @Bean is at the method level, so @Component is only an option when a class's source code is editable. @Bean can always be used, but it's more verbose. @Component is compatible with Spring's auto-detection, but @Bean requires manual class instantiation.

Can we use @bean in @component class?

@Willa yes, @Bean can be used in inside a class annotiated with @Component . "You can use the @Bean annotation in a @Configuration-annotated or in a @Component-annotated class." docs.spring.io/spring-framework/docs/current/reference/html/…

Can we have two beans with same class with different bean id in Spring?

If you define two beans of same class, without different bean id or qualifiers ( identifier) , Spring container will not be able to understand which bean to be loaded , if you try to access the bean by passing the classname and you will get NoUniqueBeanDefinitionException as there are two qualifying TestBean.

Can we have multiple beans of a same type in a class?

The limitation of this approach is that we need to manually instantiate beans using the new keyword in a typical Java-based configuration style. Therefore, if the number of beans of the same class increases, we need to register them first and create beans in the configuration class.


1 Answers

@Component and @Named are annotations that basically do the same thing, but come from different APIs.

@Component belongs to Spring API. It marks class to be autodetected as a bean and optionally allows you to specify a name for that bean (@Component("foo")). Without explicit name specification detected bean will get a default name derived from the name of its class.

@Named belongs to javax.inject API. It marks class to be autodetected as a bean and requires you to specify a name.

Spring supports both these APIs. It doesn't make sense to use both annotations at the same class since they provide the same functionality.

See also:

  • 3.10 Classpath scanning and managed components
like image 173
axtavt Avatar answered Oct 05 '22 02:10

axtavt