kaylil_01
kaylil_01

Reputation: 133

What are bean factories for, if we can use @component?

Recently I saw code like this:

@Bean
@Validated
@ConfigurationProperties(prefix = "jobrunner.filesystem")
public ExecutionFileSystemProperties executionFileSystemProperties() {
    return new ExecutionFileSystemProperties();
}

Why do that? We can use @Component and Spring will find them ourselves

P.S. Same project has @Component, @service, etc.

Upvotes: 1

Views: 77

Answers (1)

Uri Loya
Uri Loya

Reputation: 1391

from this answer by skaffman: 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.

Upvotes: 3

Related Questions