Spring's FactoryBean Interface

eidher - Oct 6 '20 - - Dev Community
interface FactoryBean<T> {
    public T getObject() throws Exception;
    public Class<?> getObjectType();
    public default boolean isSingleton() { return true; }
}
Enter fullscreen mode Exit fullscreen mode

Example

public class AppServiceFactoryBean implements FactoryBean<AppService> {
    public AppService getObject() throws Exception {
        ...
        return appService:
    }

    public Class<?> getObjectType() {
        return AppService.class;
    }
}
Enter fullscreen mode Exit fullscreen mode

FactoryBeans with Java Configuration:

Spring calls getObject() automatically.

@Configuration
public class ServiceConfig {

    @Bean
    public AppServiceFactoryBean appService() {
        return new AppServiceFactoryBean();
    }

    @Bean
    public OtherService otherService(AppService appService) {
        return new OtherService(appService);
    }
}
Enter fullscreen mode Exit fullscreen mode

Examples

Used in Spring by:

  • EmbeddedDatabaseFactoryBean
  • ProxyFactoryBean
  • JndiObjectFactoryBean
  • HibernateJpaSessionFactoryBean
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player