What is the difference between @Component and @Bean in Spring?
A) @Component is used for auto-detection, while @Bean is used for explicit bean declaration
B) @Component is used for database access, while @Bean is used for services
C) @Component is used in XML configuration, while @Bean is used in Java configuration
D) @Component is used for REST controllers, while @Bean is used for WebSocket endpoints
Answer:
A) @Component is used for auto-detection, while @Bean is used for explicit bean declaration
Explanation:
The key difference between @Component
and @Bean
in Spring lies in how they are used to declare beans. @Component
is a class-level annotation used for auto-detection of Spring-managed components through classpath scanning. When Spring scans the classpath, it detects classes annotated with @Component
and automatically registers them as beans in the Spring IoC container.
On the other hand, @Bean
is a method-level annotation used in Java configuration classes. It explicitly defines a bean and its configuration within a method. The method annotated with @Bean
returns an instance of the bean, and Spring registers this instance in the IoC container.
Reference links:
https://www.javaguides.net/p/spring-tutorial-beginners-to-expert.html