1.FactoryBean用途
FactoryBean是一个工厂bean,自定义工厂bean时需要继承FactoryBean类
FactoryBean代码如下
package org.springframework.beans.factory;
import org.springframework.lang.Nullable;
public interface FactoryBean<T> {
@Nullable
T getObject() throws Exception;
@Nullable
Class<?> getObjectType();
default boolean isSingleton() {
return true;
}
其中getObject()返回的就是bean
mybatis-spring 项目中的SqlSessionFactoryBean就是实现的FactoryBean,
public class SqlSessionFactoryBean implements FactoryBean<SqlSessionFactory>, InitializingBean, ApplicationListener<ApplicationEvent>
@Override
public SqlSessionFactory getObject() throws Exception {
if (this.sqlSessionFactory == null) {
afterPropertiesSet();
}
return this.sqlSessionFactory;
}
返回的是SqlSessionFactory示例对象
当需要获取sqlSessionFactory对象时直接调用:
applicationContext.getBean("mobile")
这里也可以获取SqlSessionFactoryBean对象,方法如下
applicationContext.getBean("&mobile")
当上面的sqlSessionFactory定义是单例时:
会将得到的sqlSessionFactory放入factorybeanObjectCache集合中存放。
对spring有一些深入了解的人都知道,一般的单例对象都是存放在singletonObjects集合中。
为什么FactoryBean生成的单例object是存放在factorybeanObjectCache中呢?
2.FactoryBean实现类及getObject方法生成的对象存放位置
FactoryBean实现类的bean存放在singletonObjects中,存放在的名称是在spring配置文件中定义的bean名称
所以当我们使用非“&”开头的时候从singletonObjects拿出是FactoryBean,这时会做一个特殊判断,
判断用户需要获取的bean是bean对象还是工厂bean本身(实现了FactoryBean的类),如果是前者,用singletonObjects拿出来
的对象是继承了FactoryBean,所以不对,这时候会从factorybeanObjectCache获取缓存,如果缓存获取不到则将从
“singletonObjects”获取到的bean强转成FactoryBean,调用它的getObject方法,再放入缓存。如果是后者则直接返回。
3.FactoryBean实现类的bean实例是什么时候生成的并放入缓存的
spring非懒加载的单例对象,一般是在调用refresh()方法时完成bean的初始化