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?
@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.
@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/…
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.
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.
@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:
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