FactoryBean
一般情况下,Spring通过反射机制利用bean的Class属性指定实现类来实例化bean。而FactoryBean是一种特殊的bean,是一个工厂bean,可以自己创建bean实例,如果一个类实现了Factorybean接口,则该类可以自己定义创建实例对象的方法,只需要实现getObject方法就好
为了区分FactoryBean和FactoryBean创建的bean实例,Spring使用了&前缀作为FactoryBean的标识名name
首先让我们看一下Spring是在什么地方,什么时刻生成FactoryBean的。
在Spring中,如果我们需要FactoryBean来帮助我们生成复杂对象,那么首先要向Spring中注册一个Factory bean,下面的调用过程就是初始化BeanFactory的过程
从上图我们可以看到,实例化一个FactoryBean的过程是什么样的,那么接下来就让我们分析一下,FactoryBean的实例化过程。
- refresh()
/**
* 刷新IOC容器
* @throws BeansException
* @throws IllegalStateException
*/
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
//准备上下文以进行刷新
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
//告诉子类重启bean工厂,Resource定位过程
//BeanDefinition的载入
//向IoC容器注册这些BeanDefinition的过程
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
// 准备bean工厂以再次上下文中使用
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
//允许在上下文子类中对bean工厂进行后处理,允许在子类重写
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
//在环境中调用已经注册好的beanFactory的后置处理器
//用于处理 BeanFactoryPostProcessor 接口
//Spring IoC 容器允许 BeanFactoryPostProcessor 在容器实例化任何 Bean 之前读取Bean 的定义,并可以修改它。
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
// 注册拦截bean创建的bean处理器,主要是用来处理beanPostProcessor
registerBeanPostProcessors(beanFactory);
/**
* BeanPostProcessors:针对于beanFactory的扩展,主要用在Bean实例化之前,读取bean的定义,并可以修改它
* BeanFactoryPostProcessor:针对于bean的扩展,主要用在Bean实例化之后,执行初始化方法前后,允许开发者对Bean实例进行修改
*/
// Initialize message source for this context.
// 初始化此上下文的消息源
initMessageSource();
// Initialize event multicaster for this context.
//初始化此上下文的事件多播器
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
// 在特定的上下文子类中初始化其他特殊bean
onRefresh();
// Check for listener beans and register them.
// 检查监听器bean并注册他们
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
// 实例化所有剩余(非懒加载的)单例对象
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
//最后一步发布相应的时间
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}
refresh()方法的作用主要是重启Spring环境,由于我们今天只关心FactoryBean相关的知识,所以我们将目光方法finishBeanFactoryInitialization()这个方法上
- finishBeanFactoryInitialization
这个方法也是AbstractApplicationContext为我们提供的一个protected方法,主要是为实例化Bean做一些准备工作
/**
* Finish the initialization of this context's bean factory,
* initializing all remaining singleton beans.
* 完成此上下文的bean工厂的初始化,初始化所有剩余的单例bean
*/
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// Initialize conversion service for this context.
//初始化上下文的转换服务
if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
beanFactory.setConversionService(
beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
}
// Register a default embedded value resolver if no bean post-processor
// (such as a PropertyPlaceholderConfigurer bean) registered any before:
// at this point, primarily for resolution in annotation attribute values.
// 2.如果beanFactory之前没有注册嵌入值解析器,则注册默认的嵌入值解析器:主要用于注解属性值的解析。
if (!beanFactory.hasEmbeddedValueResolver()) {
beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
}
// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
// 3.初始化LoadTimeWeaverAware Bean实例对象
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
for (String weaverAwareName : weaverAwareNames) {
getBean(weaverAwareName);
}
// Stop using the temporary ClassLoader for type matching.
beanFactory.setTempClassLoader(null);
// Allow for caching all bean definition metadata, not expecting further changes.
// 4.冻结所有bean定义,注册的bean定义不会被修改或进一步后处理,因为马上要创建 Bean 实例对象了
beanFactory.freezeConfiguration();
// Instantiate all remaining (non-lazy-init) singletons.
// 5.实例化所有剩余(非懒加载)单例对象
beanFactory.preInstantiateSingletons();
}
我们直接看方法的最后一行beanFactory.preInstantiateSingletons(),方法是ConfigurableListableBeanFactory为我们提供的一个接口方法,具体实现是在DefaultListableBeanFactory中实现的,主要是为了确保所有的非懒加载的Bean能够实例化,同时也会兼顾FactoryBean相关的实现,这就是我们今天所关心的。
- preInstantiateSingletons()
@Override
public void preInstantiateSingletons() throws BeansException {
if (logger.isTraceEnabled()) {
logger.trace("Pre-instantiating singletons in " + this);
}
// Iterate over a copy to allow for init methods which in turn register new bean definitions.
// While this may not be part of the regular factory bootstrap, it does otherwise work fine.
// 1.创建beanDefinitionNames的副本beanNames用于后续的遍历,以允许init等方法注册新的bean定义
List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
// Trigger initialization of all non-lazy singleton beans...
// 2.遍历beanNames,触发所有非懒加载单例bean的初始化
for (String beanName : beanNames) {
// 3.获取beanName对应的合并的BeanDefinition对象
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
// 4.bd对应的Bean实例:不是抽象类 && 是单例 && 不是懒加载
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
// 5.如果beanName对应的bean是FactoryBean
if (isFactoryBean(beanName)) {
//拿到当前beanName对应的对象
Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
//判断此对象是否是FactoryBean
if (bean instanceof FactoryBean) {
//将当前对象转换成FactoryBean
final FactoryBean<?> factory = (FactoryBean<?>) bean;
//判断这个bean是否需要急切的初始化
boolean isEagerInit;
if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>)
((SmartFactoryBean<?>) factory)::isEagerInit,
getAccessControlContext());
}
else {
isEagerInit = (factory instanceof SmartFactoryBean &&
((SmartFactoryBean<?>) factory).isEagerInit());
}
if (isEagerInit) {
// 5.3 通过beanName获取bean实例
getBean(beanName);
}
}
}
else {
// 6.如果beanName对应的bean不是FactoryBean,只是普通Bean,通过beanName获取bean实例
getBean(beanName);
}
}
}
// Trigger post-initialization callback for all applicable beans...
//用于创建完成bean之后
// 7.遍历beanNames,触发所有SmartInitializingSingleton的后初始化回调
for (String beanName : beanNames) {
// 8.拿到beanName对应的bean实例
Object singletonInstance = getSingleton(beanName);
// 9.判断singletonInstance是否实现了SmartInitializingSingleton接口
if (singletonInstance instanceof SmartInitializingSingleton) {
final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
// 10.调用SmartInitializingSingleton实现类的afterSingletonsInstantiated方法
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
smartSingleton.afterSingletonsInstantiated();
return null;
}, getAccessControlContext());
}
else {
smartSingleton.afterSingletonsInstantiated();
}
}
}
}
在这个方法中会拿到所有的beanName,然后遍历它们,如果获取到的Bean是FactoryBean的话,那么就会调用
Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
FACTORY_BEAN_PREFIX 是一个‘&’符号,在本篇文章的开头我们就说过,Spring用&+beanName来区别FactoryBean和Bean的,所以通过这种方式我们就可以实例化一个FactoryBean。
- getBean(String name)
@Override
public Object getBean(String name) throws BeansException {
return doGetBean(name, null, null, false);
}
在spring中为我们提供了很多的getBean方法,我们暂且先不关心,继续往下看。
5. doGetBean(final String name, @Nullable final Class requiredType,
@Nullable final Object[] args, boolean typeCheckOnly)
getBean最终会调用doGetBean这个才是我们实例化bean的地方
/**
* Return an instance, which may be shared or independent, of the specified bean.
* 返回指定的bean,这个bean可以是单例的或者共享的
* @param name the name of the bean to retrieve
* @param requiredType the required type of the bean to retrieve
* @param args arguments to use when creating a bean instance using explicit arguments
* (only applied when creating a new instance as opposed to retrieving an existing one)
* @param typeCheckOnly whether the instance is obtained for a type check,
* not for actual use
* @return an instance of the bean
* @throws BeansException if the bean could not be created
*/
@SuppressWarnings("unchecked")
protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
final String beanName = transformedBeanName(name);
Object bean;
// Eagerly check singleton cache for manually registered singletons.
// 急切的检查单个缓存以手动注册单例
//1.此时我们获取的是FactoryBean,在缓存中并不存在,所以反悔的sharedInstance为null
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
if (logger.isTraceEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
"' that is not fully initialized yet - a consequence of a circular reference");
}
else {
logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
}
}
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
else {
// Fail if we're already creating this bean instance:
// We're assumably within a circular reference.
//2.判断指定的bean是否正在被创建
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
// Check if bean definition exists in this factory.
//3.如果当前beanFactory中没有获取到相应的bean信息,则到父容器中去寻找
//返回的父容器是null
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// Not found -> check parent.
String nameToLookup = originalBeanName(name);
if (parentBeanFactory instanceof AbstractBeanFactory) {
return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
nameToLookup, requiredType, args, typeCheckOnly);
}
else if (args != null) {
// Delegation to parent with explicit args.
return (T) parentBeanFactory.getBean(nameToLookup, args);
}
else if (requiredType != null) {
// No args -> delegate to standard getBean method.
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
else {
return (T) parentBeanFactory.getBean(nameToLookup);
}
}
if (!typeCheckOnly) {
markBeanAsCreated(beanName);
}
try {
//4.获取到和父容器合并之后的BeanDefinition
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
//5.检查合并之后的BeanDefinition
checkMergedBeanDefinition(mbd, beanName, args);
// Guarantee initialization of beans that the current bean depends on.
//6.检查是否存在依赖
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
for (String dep : dependsOn) {
if (isDependent(beanName, dep)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
}
registerDependentBean(dep, beanName);
try {
getBean(dep);
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
}
}
}
// Create bean instance.
//创建bean的实例
if (mbd.isSingleton()) {
//7.调用getSingleton方法获取FactoryBean
sharedInstance = getSingleton(beanName, () -> {
try {
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
destroySingleton(beanName);
throw ex;
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
else if (mbd.isPrototype()) {
// It's a prototype -> create a new instance.
Object prototypeInstance = null;
try {
beforePrototypeCreation(beanName);
prototypeInstance = createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
//8.嗲用getObjectForBeanInstance方法
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
}
else {
String scopeName = mbd.getScope();
final Scope scope = this.scopes.get(scopeName);
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
}
try {
Object scopedInstance = scope.get(beanName, () -> {
beforePrototypeCreation(beanName);
try {
return createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
});
bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
}
catch (IllegalStateException ex) {
throw new BeanCreationException(beanName,
"Scope '" + scopeName + "' is not active for the current thread; consider " +
"defining a scoped proxy for this bean if you intend to refer to it from a singleton",
ex);
}
}
}
catch (BeansException ex) {
cleanupAfterBeanCreationFailure(beanName);
throw ex;
}
}
// Check if required type matches the type of the actual bean instance.
if (requiredType != null && !requiredType.isInstance(bean)) {
try {
T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
if (convertedBean == null) {
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
return convertedBean;
}
catch (TypeMismatchException ex) {
if (logger.isTraceEnabled()) {
logger.trace("Failed to convert bean '" + name + "' to required type '" +
ClassUtils.getQualifiedName(requiredType) + "'", ex);
}
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
}
return (T) bean;
}
我们暂时先只关心mbd.isSingleton()里面的逻辑,这块是创建一个单例bean,具体的逻辑已经写到上面的注释上了,在调用getObjectForBeanInstance方法之前,其实我们已经获取到了一个Factory Bean,接下来让我们看看getObjectForBeanInstance中做了什么。
@Override
protected Object getObjectForBeanInstance(
Object beanInstance, String name, String beanName, @Nullable RootBeanDefinition mbd) {
//其实这个currentlyCreatedBean是什么暂时没有搞明白,不过根据下面registerDependentBean方法可以推断出,这个currentlyCreatedBean应该是一个和当前bean存在依赖关系的bean的名称
String currentlyCreatedBean = this.currentlyCreatedBean.get();
if (currentlyCreatedBean != null) {
//注册bean的依赖关系
registerDependentBean(beanName, currentlyCreatedBean);
}
//调用父类的方法
return super.getObjectForBeanInstance(beanInstance, name, beanName, mbd);
}
在调用父类方法前首先判断一下是否存在依赖关系的bean,接下来我们看一下父类中是如何实现的
protected Object getObjectForBeanInstance(
Object beanInstance, String name, String beanName, @Nullable RootBeanDefinition mbd) {
// Don't let calling code try to dereference the factory if the bean isn't a factory.
//判断BeanName是否以&开头的,这里肯定不是
if (BeanFactoryUtils.isFactoryDereference(name)) {
if (beanInstance instanceof NullBean) {
return beanInstance;
}
if (!(beanInstance instanceof FactoryBean)) {
throw new BeanIsNotAFactoryException(transformedBeanName(name), beanInstance.getClass());
}
}
// Now we have the bean instance, which may be a normal bean or a FactoryBean.
// If it's a FactoryBean, we use it to create a bean instance, unless the
// caller actually wants a reference to the factory.
//如果当前bean不是FactoryBean或者是以&开头的,由于当前的name是以&开头的,所以直接返回当前的bean实例
if (!(beanInstance instanceof FactoryBean) || BeanFactoryUtils.isFactoryDereference(name)) {
return beanInstance;
}
Object object = null;
if (mbd == null) {
object = getCachedObjectForFactoryBean(beanName);
}
if (object == null) {
// Return bean instance from factory.
FactoryBean<?> factory = (FactoryBean<?>) beanInstance;
// Caches object obtained from FactoryBean if it is a singleton.
if (mbd == null && containsBeanDefinition(beanName)) {
mbd = getMergedLocalBeanDefinition(beanName);
}
boolean synthetic = (mbd != null && mbd.isSynthetic());
object = getObjectFromFactoryBean(factory, beanName, !synthetic);
}
return object;
}
当然在我们的getObjectForBeanInstance方法中,还存在很多判断,但是我们今天只探讨的是如何得到一个FactoryBean对象,有关getBean的相关知识,下次在进行分析。