Video in progress
Which creational pattern are Spring's `@Bean` method and the `FactoryBean` interface examples of, and how do they differ?
Both are Factory: they move the logic for creating a bean out of the container and into your code. A @Bean method is simple and enough in most cases; FactoryBean is for reusable, framework-level, complex creation logic.
📖 Answer
@Bean is the most common factory method:
@Configuration
class HttpConfig {
@Bean
RestClient paymentClient(RestClient.Builder builder, PaymentProps props) {
return builder.baseUrl(props.url())
.defaultHeader("X-Key", props.key())
.build();
}
}
Spring calls the method and makes the returned object a bean. There can be any logic inside.
FactoryBean<T> is a factory that is itself a bean:
public class SignerFactoryBean implements FactoryBean<Signer> {
public Signer getObject() { return loadKeyAndBuildSigner(); }
public Class<?> getObjectType() { return Signer.class; }
}
If you ask the context for signer, you get the result of getObject(), not the factory. If you need the factory itself, put & before the name: getBean("&signer").
In practice you rarely write a FactoryBean yourself, but it's everywhere: LocalContainerEntityManagerFactoryBean, Spring Data repositories (JpaRepositoryFactoryBean), ProxyFactoryBean. In application code @Bean is enough in 95% of cases.
Sign up to mark studied questions and save your progress.