Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are @Bean and @Component annotations the same but for different targets in Spring Framework? [duplicate]

Am I correct, thinking that @Bean and @Component annotations are the same, but first is for classes and another is for methods?

In both cases container just creates appropriate beans, right?

like image 274
Suzan Cioc Avatar asked Nov 23 '14 16:11

Suzan Cioc


People also ask

Is @component and @bean same?

There are some important implications we should note because of the differences between @Component and @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.

What is the difference between @bean and @component in Spring boot?

@Component is a class level annotation whereas @Bean is a method level annotation and name of the method serves as the bean name. @Component need not to be used with the @Configuration annotation where as @Bean annotation has to be used within the class which is annotated with @Configuration.

Can we use @component and @bean in same class?

In the component classes, we can use any valid annotation along with @Bean method and it's parameters, exactly the same way we use them in @Configuration classes (e.g. @Lazy, @Qualifier, @Primary etc).

Does @component create a bean?

No. It is used to explicitly declare a single bean, rather than letting Spring do it automatically. If any class is annotated with @Component it will be automatically detect by using classpath scan. We should use @bean, if you want specific implementation based on dynamic condition.


1 Answers

Not quite. They belong to different concepts.

@Component is a stereotype annotation. A class annotated with this annotation will be auto detected during class path scanning. See also Spring reference documentation chapter 5.10. Other than that the @Bean annotation belongs to the Java configuration feature. Within a configuration class this annotation is used to mark methods that define beans.

like image 190
Christian Frommeyer Avatar answered Oct 20 '22 00:10

Christian Frommeyer