FactoryBean工厂

继承FactoryBean工厂

@Controller
public class GetBeanFactory implements FactoryBean<A> {
    @Override
    public A getObject() throws Exception {
        return new A();
    }

    @Override
    public Class<?> getObjectType() {
        return A.class;
    }
}

调用

  ApplicationContext context =
                new AnnotationConfigApplicationContext("org.example.mvc");
        System.out.println(context.getBean("getBeanFactory"));
        System.out.println(context.getBean("&getBeanFactory"));

context.getBean("getBeanFactory")输出的是对象A
context.getBean("&getBeanFactory")输出的是对象A的工厂对象、

最核心代码AbstractBeanFactory-->getObjectForBeanInstance
如果是&开头的判断这个实例是不是FactoryBean,是则直接返回
如果不是&开头,则强转为FactoryBean工厂对象,调用doObject()方法,拿到实例返回

 protected Object getObjectForBeanInstance(Object beanInstance, String name, String beanName, @Nullable RootBeanDefinition mbd) {
       //这里面是是看是否是&符号考试
        if (BeanFactoryUtils.isFactoryDereference(name)) {
            if (beanInstance instanceof NullBean) {
                return beanInstance;
            } else if (!(beanInstance instanceof FactoryBean)) {
                throw new BeanIsNotAFactoryException(beanName, beanInstance.getClass());
            } else {
                if (mbd != null) {
                    mbd.isFactoryBean = true;
                }
             //返回工厂实例
                return beanInstance;
            }
        } else if (!(beanInstance instanceof FactoryBean)) {
            return beanInstance;
        } else {
            Object object = null;
            if (mbd != null) {
                mbd.isFactoryBean = true;
            } else {
            //从缓存里面拿
                object = this.getCachedObjectForFactoryBean(beanName);
            }
            if (object == null) {
                //强转为工厂对象
                FactoryBean<?> factory = (FactoryBean)beanInstance;
                if (mbd == null && this.containsBeanDefinition(beanName)) {
                    mbd = this.getMergedLocalBeanDefinition(beanName);
                }
                boolean synthetic = mbd != null && mbd.isSynthetic();
                //这里面调用dogetObject方法
                object = this.getObjectFromFactoryBean(factory, beanName, !synthetic);
            }

            return object;
        }
    }
上一篇:Spring学习笔记--高级特性之FactoryBean


下一篇:Spring源码之BeanFactory与FactoryBean