BeanDefinition和Bean

Spring中Bean的注入触及两部分:

  1. BeanDefinition
  2. Bean

两个目标存在先后顺序,先注入BeanDefinition之后才履行Bean目标的注入。

那么两者有什么关联呢?

BeanDefinition和Bean的联系:可以了解为BeanDefinition是Bean的包装类,类似Java中类和特点的联系。

BeanDefinition是对Bean目标的包装,BeanDefinition中封装了Bean相关的描绘,比如bean目标,bean的单例还是原型、bean的父级、懒加载办法等等。

public interface BeanDefinition extends AttributeAccessor, BeanMetadataElement {
	void setScope(@Nullable String scope);
	@Nullable
	String getScope();
	void setLazyInit(boolean lazyInit);
	boolean isLazyInit();
}
//bean的原数据
public interface BeanMetadataElement {
	@Nullable
	Object getSource();
}

在BeanDefinition中承继了BeanMetadataElement,该类是Bean的原数据,该类中实例化了Bean目标为Object。因而在BeanDefinition中调用getSource就可以获取到Bean目标。

分清楚BeanDefinition和Bean之后再看BeanDefinition的注入,因为只有注入了BeanDefinition才会注入后续的Bean。

BeanDefinition的注入

BeanDefinitionRegistry接口

BeanDefinitin的注入经过接口BeanDefinitionRegistry笼统了各种对BeanDefinition的操作,例如

  • BeanDefinitionRegistry#registerBeanDefinition(注入到beanDefinition中)
  • BeanDefinitionRegistry#removeBeanDefinition(从beanDefinition容器中移除)
  • BeanDefinitionRegistry#getBeanDefinition(获取BeanDefinition)
public interface BeanDefinitionRegistry extends AliasRegistry {
	void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
			throws BeanDefinitionStoreException;
	void removeBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;
	BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;
	boolean containsBeanDefinition(String beanName);
	String[] getBeanDefinitionNames();
	int getBeanDefinitionCount();
	boolean isBeanNameInUse(String beanName);
}

该接口是操作BeanDefinition的根底接口,该类是一个接口类型并不是一个笼统类,因而该接口中不会界说任何BeanDefinition的容器,BeanDefinition的容器只在各完成类中界说并运用。任何需求操作BeanDefinition的完成都需求完成该接口。

BeanDefinitionRegistry的完成类

Spring中Bean注入源码分析

找到操作BeanDefinition的接口就可以经过接口检查接口的完成类,从而找到BeanDefinition的应用。

BeanDefinition常见的几个完成类有:

  • DefaultListableBeanFactory

  • SimpleBeanDefinitionRegistry

SimpleBeanDefinitionRegistry

public class SimpleBeanDefinitionRegistry extends SimpleAliasRegistry implements BeanDefinitionRegistry {
	/**beanDefinition的容器,经过ConcurrentHashMap完成. */
	private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(64);
	//该类的完成办法只是完成了最简略的beanDefinition的注入,在Java开发环境中并不会运用该完成类
	@Override
	public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
			throws BeanDefinitionStoreException {
		Assert.hasText(beanName, "'beanName' must not be empty");
		Assert.notNull(beanDefinition, "BeanDefinition must not be null");
		this.beanDefinitionMap.put(beanName, beanDefinition);
	}
}

该完成类中只做了最简略的注入功能,没有任何的逻辑处理,因而在实际开发过程中Spring并不会运用该类。

DefaultListableBeanFactory

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
		//beanDefinition的容器
		private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(256);
		//向BeanFactory中注入BeanDefinition
		public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) throws BeanDefinitionStoreException {
			Assert.hasText(beanName, "Bean name must not be empty");
			Assert.notNull(beanDefinition, "BeanDefinition must not be null");
			if (beanDefinition instanceof AbstractBeanDefinition) {
				try {
					((AbstractBeanDefinition) beanDefinition).validate();
				}
				catch (BeanDefinitionValidationException ex) {
					throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
							"Validation of bean definition failed", ex);
				}
			}
			BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName);
			//判别beanDefinition容器中是否已存在该beanDefinition
			if (existingDefinition != null) {
				//是否可以掩盖
				if (!isAllowBeanDefinitionOverriding()) {
					throw new BeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition);
				} else if (existingDefinition.getRole() < beanDefinition.getRole()) {
					// e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE
					if (logger.isInfoEnabled()) {
						logger.info("Overriding user-defined bean definition for bean '" + beanName +
								"' with a framework-generated bean definition: replacing [" +
								existingDefinition + "] with [" + beanDefinition + "]");
					}
				} else if (!beanDefinition.equals(existingDefinition)) {
					if (logger.isDebugEnabled()) {
						logger.debug("Overriding bean definition for bean '" + beanName +
								"' with a different definition: replacing [" + existingDefinition +
								"] with [" + beanDefinition + "]");
					}
				} else {
					if (logger.isTraceEnabled()) {
						logger.trace("Overriding bean definition for bean '" + beanName +
								"' with an equivalent definition: replacing [" + existingDefinition +
								"] with [" + beanDefinition + "]");
					}
				}
				//掩盖beanDefinition
				this.beanDefinitionMap.put(beanName, beanDefinition);
			} else { //容器中不存在该beanDefinition的处理
				if (hasBeanCreationStarted()) {
					synchronized (this.beanDefinitionMap) { //对beanDefinition加锁
						//注入该beanDefinition
						this.beanDefinitionMap.put(beanName, beanDefinition);
						List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1);
						updatedDefinitions.addAll(this.beanDefinitionNames);
						updatedDefinitions.add(beanName);
						this.beanDefinitionNames = updatedDefinitions;
						if (this.manualSingletonNames.contains(beanName)) {
							Set<String> updatedSingletons = new LinkedHashSet<>(this.manualSingletonNames);
							updatedSingletons.remove(beanName);
							this.manualSingletonNames = updatedSingletons;
						}
					}
				}
				else {
					// Still in startup registration phase
					this.beanDefinitionMap.put(beanName, beanDefinition);
					this.beanDefinitionNames.add(beanName);
					this.manualSingletonNames.remove(beanName);
				}
				this.frozenBeanDefinitionNames = null;
			}
		if (existingDefinition != null || containsSingleton(beanName)) {
			resetBeanDefinition(beanName);
		}
	}
}

DefaultListableBeanFactory是默许运用的注入BeanDefinition的完成类,可以看到该完成类中对注入BeanDefinition做了许多的逻辑判别,日常开发发动容器过程中都会运用该完成类注入BeanDefinition进行后续的Bean注入。

Bean的注入

BeanDefinition注入后后续履行Bean的注入,bean注入的办法也是将bean注入到bean的容器中,因而在Spring中BeanDefinition和Bean都是经过容器化的办法操作的,那么在Bean的注入中也经过对应的接口界说对Bean的操作,该接口便是SingletonBeanRegistry

SingletonBeanRegistry接口

该接口完成了对Bean的操作:

  • SingletonBeanRegistry#registerSingleton(将bean注入到容器中)
  • SingletonBeanRegistry#getSingleton(从容器中获取bean)
public interface SingletonBeanRegistry {
	//注入bean
	void registerSingleton(String beanName, Object singletonObject);
	//获取bean
	@Nullable
	Object getSingleton(String beanName);
	//是否存在bean
	boolean containsSingleton(String beanName);
	String[] getSingletonNames();
	int getSingletonCount();
	Object getSingletonMutex();
}

SingletonBeanRegistry的完成类

SingletonBeanRegistry的完成类有多个,分别为:

  • AbstractBeanFactory
  • DefaultListableBeanFactory
  • DefaultSingletonBeanRegistry
  • FactoryBeanRegistrySupport
  • AbstractAutowireCapableBeanFactory

下面说两个有代表性的:AbstractBeanFactory和DefaultSingletonBeanRegistry

AbstractBeanFactory

该完成类是一个笼统类,即该类是bean的工厂类,其中首要完成的是可以复用的详细逻辑,该笼统类中包含获取bean、beanPostProcessor、初始化bean、毁掉bean等对bean的操作笼统类。

public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
	//获取bean的办法平常运用ApplicationContext便是终究调用该办法
	public Object getBean(String name) throws BeansException {
		return doGetBean(name, null, null, false);
	}
	@Override
	public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
		return doGetBean(name, requiredType, null, false);
	}
	@Override
	public Object getBean(String name, Object... args) throws BeansException {
		return doGetBean(name, null, args, false);
	}
	public <T> T getBean(String name, @Nullable Class<T> requiredType, @Nullable Object... args)
			throws BeansException {
		return doGetBean(name, requiredType, args, false);
	}
	/**
	* 从容器中获取bean的首要逻辑
	*/
	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.
		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 {
			//省掉部分代码
			try {
				//先获取beanDefinition
				final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
				checkMergedBeanDefinition(mbd, beanName, args);
				// Guarantee initialization of beans that the current bean depends on.
				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);
						}
					}
				}
				// 单例形式下获取bean的办法
				if (mbd.isSingleton()) {
					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()) {//原型形式下的bean的获取
					// It's a prototype -> create a new instance.
					Object prototypeInstance = null;
					try {
						beforePrototypeCreation(beanName);
						//原型形式每次都需求创立bean
						prototypeInstance = createBean(beanName, mbd, args);
					}
					finally {
						afterPrototypeCreation(beanName);
					}
					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;
			}
		}
		//省掉部分代码
		return (T) bean;
	}
	//将完成beanPostProcessor的完成类加入到链表中用于对bean的前置或者后置处理
	@Override
	public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
		Assert.notNull(beanPostProcessor, "BeanPostProcessor must not be null");
		// Remove from old position, if any
		this.beanPostProcessors.remove(beanPostProcessor);
		// Track whether it is instantiation/destruction aware
		if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) {
			this.hasInstantiationAwareBeanPostProcessors = true;
		}
		if (beanPostProcessor instanceof DestructionAwareBeanPostProcessor) {
			this.hasDestructionAwareBeanPostProcessors = true;
		}
		// Add to end of list
		this.beanPostProcessors.add(beanPostProcessor);
	}
	//毁掉bean的办法
	@Override
	public void destroyBean(String beanName, Object beanInstance) {
		destroyBean(beanName, beanInstance, getMergedLocalBeanDefinition(beanName));
	}
	protected void destroyBean(String beanName, Object bean, RootBeanDefinition mbd) {
		new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), getAccessControlContext()).destroy();
	}
}

DefaultSingletonBeanRegistry

该完成类经过姓名也可以推断出该完成类是对单例bean的注入,该类中完成了bean的一切容器,平常开发过程中Spring容器发动便是运用了该完成类中的容器,该完成类是对bean终究注入的完成,触及的四个容器首要有:

  • singletonObjects
  • singletonFactories
  • earlySingletonObjects
  • registeredSingletons

四个容器其中三个的核心作用是处理循环依靠,这里不展开说。

找一条主线整理下Bean注入的过程,当BeanDefinition注入成功后,后续履行bean的注入,以AbstractAutowireCapableBeanFactory的完成为例,该完成类中会对bean的注入,整个注入的链路如下:

  1. 获取资源数据:CommonAnnotationBeanPostProcessor#autowireResource
  2. 经过beanName解析bean:AbstractAutowireCapableBeanFactory#resolveBeanByName
  3. 调用笼统类中获取bean:AbstractBeanFactory#getBean
  4. 履行笼统类中获取bean的核心逻辑:AbstractBeanFactory#doGetBean
  5. bean不存在时创立bean:AbstractAutowireCapableBeanFactory#createBean
  6. 获取单例bean:efaultSingletonBeanRegistry#getSingleton
  7. 单例bean不存在将类注入到容器中:DefaultSingletonBeanRegistry#addSingleton
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
	//单例bean的容器,开发过程中获取的bean都是从该容器中获取的:即所谓的一级缓存
	private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
	//单例bean的beanFactory的容器:即所谓的三级缓存
	private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);
	//提早初始化的bean的容器,该容器的bean并没有任何特点值只是提早将bean注入到该容器中用于后续的判别
	//即所谓的二级缓存
	private final Map<String, Object> earlySingletonObjects = new HashMap<>(16);
	//已注册的单例bean的beanName列表
	private final Set<String> registeredSingletons = new LinkedHashSet<>(256);
	//注入bean的办法
	public void registerSingleton(String beanName, Object singletonObject) throws IllegalStateException {
		Assert.notNull(beanName, "Bean name must not be null");
		Assert.notNull(singletonObject, "Singleton object must not be null");
		synchronized (this.singletonObjects) {
			Object oldObject = this.singletonObjects.get(beanName);
			if (oldObject != null) {
				throw new IllegalStateException("Could not register object [" + singletonObject +
												"] under bean name '" + beanName + "': there is already object [" + oldObject + "] bound");
			}
			addSingleton(beanName, singletonObject);
		}
	}
	/**
	* 将bean注入容器中,操作四个容器首要用于bean的循环依靠问题
	*/
	protected void addSingleton(String beanName, Object singletonObject) {
		synchronized (this.singletonObjects) {
			this.singletonObjects.put(beanName, singletonObject);
			this.singletonFactories.remove(beanName);
			this.earlySingletonObjects.remove(beanName);
			this.registeredSingletons.add(beanName);
		}
	}
}

总结

以上便是对bean注入从源码的整理,该整理首要从bean注入前的预备(beanDefinition的注入)和bean注入的完成来完成,从整个整理中学到最多的首要有两点:

  • 笼统的思维:在BeanDefinition的完成和Bean的完成逻辑中,都完成高度笼统而且遵从单一原则和高度笼统,代码的可扩展性和复用性很高,咱们作为开发者也可以经过Spring暴露的各种Registry接口完成对Bean的操作。
  • 容器化思维:从BeanDefinition和Bean的注入来看,整个的完成思路都是根据容器化思维来完成的,将开发中需求关心的目标都实例化到容器中,开发者在运用时只要从容器中获取即可,而且获取bean的办法也很灵敏,开发者在运用和扩展性上更便利。

关于源码的学习自己了解来说并不是背其中的代码,而是学习大佬完成代码的思维,为什么可以笼统出扩展性这么高的代码,而且从源头整理下来都能很轻松的按照主线一步一步整理到目的地,这也是每个开发者需求学习的当地,提高自己代码的可读性和可扩展性,可以掌握面向目标的核心:封装、承继、多态