Spring: @Component versus @Bean Spring: @Component versus @Bean java java

Spring: @Component versus @Bean


@Component and @Bean do two quite different things, and shouldn't be confused.

@Component (and @Service and @Repository) are used to auto-detect and auto-configure beans using classpath scanning. There's an implicit one-to-one mapping between the annotated class and the bean (i.e. one bean per class). Control of wiring is quite limited with this approach, since it's purely declarative.

@Bean is used to explicitly declare a single bean, rather than letting Spring do it automatically as above. It decouples the declaration of the bean from the class definition, and lets you create and configure beans exactly how you choose.

To answer your question...

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

Sure, probably; but they chose not to, since the two are quite different. Spring's already confusing enough without muddying the waters further.


@ComponentPreferable for component scanning and automatic wiring.

When should you use @Bean?

Sometimes automatic configuration is not an option. When? Let's imagine that you want to wire components from 3rd-party libraries (you don't have the source code so you can't annotate its classes with @Component), so automatic configuration is not possible.

The @Bean annotation returns an object that spring should register as bean in application context. The body of the method bears the logic responsible for creating the instance.


Let's consider I want specific implementation depending on some dynamic state.@Bean is perfect for that case.

@Bean@Scope("prototype")public SomeService someService() {    switch (state) {    case 1:        return new Impl1();    case 2:        return new Impl2();    case 3:        return new Impl3();    default:        return new Impl();    }}

However there is no way to do that with @Component.