Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (2.6k points)
I understand that @Component annotation was introduced in spring 2.5 in order to get rid of xml bean definition by using classpath scanning.

@Bean was introduced in spring 3.0 and can be used with @Configuration in order to fully get rid of xml file and use java config instead.

Would it have been possible to re-use the @Component annotation instead of introducing @Bean annotation? My understanding is that the final goal is to create beans in both cases.

1 Answer

0 votes
by (46k points)

@Component and @Bean do two considerably diverse things, and shouldn't be complicated.

@Component (and @Service and @Repository) are applied to auto-detect and auto-configure beans practicing classpath scanning. There's an absolute one-to-one mapping among the annotated class and the bean (i.e. one bean per class). Control of wiring is quite restricted with this approach, as it's completely declarative.

@Bean is practiced to explicitly declare a single bean, fairly than letting Spring do it automatically as foregoing. It decouples the presentation of the bean from the class definition and lets you generate and configure beans exactly how you choose.

To clarify your question...

would it have been possible to re-use the @Component annotation instead of introducing @Bean annotation?

Sure, apparently; but they preferred not to as the two are quite distinct. Spring's previously confusing adequately without muddying the waters moreover.

Related questions

0 votes
1 answer
asked Jul 31, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Oct 31, 2019 in Java by Anvi (10.2k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...