ObjectFactory 与 BeanFactory 的区别

2021-01-28

ObjectFactory 与 BeanFactory 都提供查找实例的能力。

按照单词理解

  • ObjectFactory 是对象的工厂
  • BeanFactory 是 Bean 的工厂


ObjectFactory 接口通常用于封装一个通用的工厂。仅关注一个或一种类型的对象的生产(查找)。

ObjectFactoryCreatingFactoryBean 可以实现 Bean 的延迟加载;TargetBeanObjectFactory 是其静态内部类,实现了 ObjectFactory 接口,用于生产 targetBeanName 的 Bean 对象。

public class ObjectFactoryCreatingFactoryBean extends AbstractFactoryBean<ObjectFactory<Object>> {
    //设置目标 Bean 名称
    private String targetBeanName;
    public void setTargetBeanName(String targetBeanName) {
        this.targetBeanName = targetBeanName;
    }
    public void afterPropertiesSet() throws Exception {
        Assert.hasText(this.targetBeanName, "Property 'targetBeanName' is required");
        super.afterPropertiesSet();
    }
    public Class<?> getObjectType() {
        return ObjectFactory.class;
    }
    //返回实现 ObjectFactory 的静态内部类 TargetBeanObjectFactory
    protected ObjectFactory<Object> createInstance() {
        return new TargetBeanObjectFactory(getBeanFactory(), this.targetBeanName);
    }
    private static class TargetBeanObjectFactory implements ObjectFactory<Object>, Serializable {
        private final BeanFactory beanFactory;
        private final String targetBeanName;
        public TargetBeanObjectFactory(BeanFactory beanFactory, String targetBeanName) {
            this.beanFactory = beanFactory;
            this.targetBeanName = targetBeanName;
        }
        //生成对象的能力,来自于通过构造方法持有的 BeanFactory 对象
        public Object getObject() throws BeansException {
            return this.beanFactory.getBean(this.targetBeanName);
        }
    }
}

 

ConstXiong 备案号:苏ICP备16009629号-3