Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Difference between @Bean and @Component annotation in Spring.
Spring supports multiple types annotations such as @Component,@Controller,@service @Repository and @Bean. All theses can be found under the org.springframework.stereotype package.
When classes in our application are annotated with any of the above mentioned annotation then during project startup spring scan(using @componentScan) each class and inject the instance of the classes to the IOC container. Another thing the @ComponentScan would do is running the methods with @Bean on it and restore the return object to the Ioc Container as a bean.
| Sr. No. | Key | @Bean | @Component |
|---|---|---|---|
| 1 |
Auto detection |
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. |
| 2 |
Spring Container |
Bean can be created even class is outside the spring container |
We can’t create bean if class is outside spring container |
| 3 |
Class/Method Level Annotation |
It is a method level annotation |
It is a class level annotation |
| 4 |
@Configuration |
It works only when class is also annotated with @Configuration |
It works without @Configuration annotation |
| 5 |
Use Case |
We should use @bean, if you want specific implementation based on dynamic condition. |
We can’t write specific implementation based on dynamic condition |
Example of @Component
@Component
public class Pizza{
........
}
Example of @Bean
@Configuration
class AppConfiguration{
@Bean
public User getUse(){
return new User();
}
} Advertisements
