BeanFactory 和 FactoryBean的区别
-
相同点:都是用来创建bean对象的
-
不同点:
- 使用BeanFactory创建对象的时候,必须遵循严格的生命周期流程,太复杂了。
- 通过实现FactoryBean接口,可以简单的自定义某个对象的创建,并在创建完成后,将其交给spring管理
Spring源码对FactoryBean注释中:
The container is only responsible for managing the lifecycle of the FactoryBean instance, not the lifecycle of the objects created by the FactoryBean. Therefore, a destroy method on an exposed bean object (such as java.io.Closeable.close() will not be called automatically. Instead, a FactoryBean should implement DisposableBean and delegate any such close call to the underlying object.
翻译:
容器只负责管理FactoryBean 实例的生命周期,而不是FactoryBean 创建的对象的生命周期。因此,暴露的 bean 对象(例如 java.io.Closeable.close() 上的销毁方法不会被自动调用。相反,FactoryBean 应该实现 DisposableBean 并将任何此类关闭调用委托给底层对象
也就是说,对象有FactoryBean创建,spring只负责管理由FactoryBean创建好的对象
public interface FactoryBean<T> { String OBJECT_TYPE_ATTRIBUTE = "factoryBeanObjectType"; // 自定义创建对象的过程(new,反射,动态代理) @Nullable T getObject() throws Exception; // 获取返回对象的类型 @Nullable Class<?> getObjectType(); //判断是否为单例对象 default boolean isSingleton() { return true; } }