b、在中篇会正式经历一套生命周期流程
getBean() -> doGetBean() -> createBean() -> doCreateBean() -> createBeanInstance() -> populateBean() -> initializeBean() 流程
1、AbstractBeanFactory#getBean()
此处开始进行对象的获取也就是核心步骤
@Overridepublic Object getBean(String name) throws BeansException {// 此方法是实际获取bean的方法,也是触发依赖注入的方法return doGetBean(name, null, null, false);}
2、AbstractBeanFactory#doGetBean()
protected <T> T doGetBean(String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)throws BeansException {/*** 提取对应的beanName,有人可能会认为此处直接使用即可,为什么还要进行转换呢,原因在于当bean对象实现FactoryBean接口之后就会变成&beanName,同时如果存在别名,也需要把别名进行转换*/String beanName = transformedBeanName(name);Object bean;// Eagerly check singleton cache for manually registered singletons./**提前检查单例缓存中是否有手动注册的单例对象,跟循环依赖有关联*/Object sharedInstance = getSingleton(beanName);// 如果bean的单例对象找到了,且没有创建bean实例时要使用的参数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 + "'");}}// 返回对象的实例,这句话的重点在于当你实现了FactoryBean接口的对象,需要获取具体的对象的时候就需要此方法来进行获取了bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);}else {// Fail if we're already creating this bean instance:// We're assumably within a circular reference.// 当对象都是单例的时候会尝试解决循环依赖的问题,但是原型模式下如果存在循环依赖的情况,那么直接抛出异常if (isPrototypeCurrentlyInCreation(beanName)) {throw new BeanCurrentlyInCreationException(beanName);}// Check if bean definition exists in this factory.// 如果bean定义不存在,就检查父工厂是否有BeanFactory parentBeanFactory = getParentBeanFactory();// 如果beanDefinitionMap中也就是在所有已经加载的类中不包含beanName,那么就尝试从父容器中获取if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {// Not found -> check parent.// 获取name对应的规范名称【全类名】,如果name前面有'&',则会返回'&'+规范名称【全类名】String nameToLookup = originalBeanName(name);// 如果父工厂是AbstractBeanFactory的实例if (parentBeanFactory instanceof AbstractBeanFactory) {// 调用父工厂的doGetBean方法,就是该方法。【递归】return ((AbstractBeanFactory) parentBeanFactory).doGetBean(nameToLookup, requiredType, args, typeCheckOnly);}else if (args != null) {// Delegation to parent with explicit args.// 如果有创建bean实例时要使用的参数// Delegation to parent with explicit args. 使用显示参数委派给父工厂// 使用父工厂获取该bean对象,通bean全类名和创建bean实例时要使用的参数return (T) parentBeanFactory.getBean(nameToLookup, args);}else if (requiredType != null) {// No args -> delegate to standard getBean method.// 没有创建bean实例时要使用的参数 -> 委托给标准的getBean方法。// 使用父工厂获取该bean对象,通bean全类名和所需的bean类型return parentBeanFactory.getBean(nameToLookup, requiredType);}else {// 使用父工厂获取bean,通过bean全类名return (T) parentBeanFactory.getBean(nameToLookup);}}// 如果不是做类型检查,那么表示要创建bean,此处在集合中做一个记录if (!typeCheckOnly) {// 为beanName标记为已经创建(或将要创建)markBeanAsCreated(beanName);}try {// 此处做了BeanDefinition对象的转换,当我们从xml文件中加载beandefinition对象的时候,封装的对象是GenericBeanDefinition,// 此处要做类型转换,如果是子类bean的话,会合并父类的相关属性RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);// 检查mbd的合法性,不合格会引发验证异常checkMergedBeanDefinition(mbd, beanName, args);// Guarantee initialization of beans that the current bean depends on.// 如果存在依赖的bean的话,那么则优先实例化依赖的beanString[] dependsOn = mbd.getDependsOn();if (dependsOn != null) {// 如果存在依赖,则需要递归实例化依赖的beanfor (String dep : dependsOn) {// 如果beanName已注册依赖于dependentBeanName的关系if (isDependent(beanName, dep)) {throw new BeanCreationException(mbd.getResourceDescription(), beanName,"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");}// 注册各个bean的依赖关系,方便进行销毁registerDependentBean(dep, beanName);try {// 递归优先实例化被依赖的BeangetBean(dep);}// 捕捉为找到BeanDefinition异常:'beanName'依赖于缺少的bean'dep'catch (NoSuchBeanDefinitionException ex) {throw new BeanCreationException(mbd.getResourceDescription(), beanName,"'" + beanName + "' depends on missing bean '" + dep + "'", ex);}}}// Create bean instance.// 创建bean的实例对象if (mbd.isSingleton()) {// 返回以beanName的(原始)单例对象,如果尚未注册,则使用singletonFactory创建并注册一个对象:sharedInstance = getSingleton(beanName, () -> {try {// 为给定的合并后BeanDefinition(和参数)创建一个bean实例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.// 显示地从单例缓存中删除实例:它可能是由创建过程急切地放在那里,以允许循环引用解析。还要删除// 接收到该Bean临时引用的任何Bean// 销毁给定的bean。如果找到相应的一次性Bean实例,则委托给destoryBeandestroySingleton(beanName);// 重新抛出exthrow ex;}});// 从beanInstance中获取公开的Bean对象,主要处理beanInstance是FactoryBean对象的情况,如果不是// FactoryBean会直接返回beanInstance实例bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);}// 原型模式的bean对象创建else if (mbd.isPrototype()) {// It's a prototype -> create a new instance.// 它是一个原型 -> 创建一个新实例// 定义prototype实例Object prototypeInstance = null;try {// 创建Prototype对象前的准备工作,默认实现将beanName添加到prototypesCurrentlyInCreation中beforePrototypeCreation(beanName);// 为mbd(和参数)创建一个bean实例prototypeInstance = createBean(beanName, mbd, args);}finally {// 创建完prototype实例后的回调,默认是将beanName从prototypesCurrentlyInCreation移除afterPrototypeCreation(beanName);}// 从beanInstance中获取公开的Bean对象,主要处理beanInstance是FactoryBean对象的情况,如果不是// FactoryBean会直接返回beanInstance实例bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);}else {// 指定的scope上实例化beanString scopeName = mbd.getScope();if (!StringUtils.hasLength(scopeName)) {throw new IllegalStateException("No scope name defined for bean ´" + beanName + "'");}// 从scopes中获取scopeName对于的Scope对象Scope scope = this.scopes.get(scopeName);// 如果scope为nullif (scope == null) {// 抛出非法状态异常:没有名为'scopeName'的scope注册throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");}try {// 从scope中获取beanName对应的实例对象Object scopedInstance = scope.get(beanName, () -> {// 创建Prototype对象前的准备工作,默认实现 将beanName添加到prototypesCurrentlyInCreation中beforePrototypeCreation(beanName);try {// 为mbd(和参数)创建一个bean实例return createBean(beanName, mbd, args);}finally {// 创建完prototype实例后的回调,默认是将beanName从prototypesCurrentlyInCreation移除afterPrototypeCreation(beanName);}});// 从beanInstance中获取公开的Bean对象,主要处理beanInstance是FactoryBean对象的情况,如果不是// FactoryBean会直接返回beanInstance实例bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);}catch (IllegalStateException ex) {// 捕捉非法状态异常// 抛出Bean创建异常:作用域 'scopeName' 对于当前线程是不活动的;如果您打算从单个实例引用它,请考虑为此// beanDefinition一个作用域代理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) {// 捕捉获取Bean对象抛出的Bean异常// 在Bean创建失败后,对缓存的元数据执行适当的清理cleanupAfterBeanCreationFailure(beanName);// 重新抛出exthrow ex;}}// Check if required type matches the type of the actual bean instance.// 检查requiredType是否与实际Bean实例的类型匹配// 如果requiredType不为null&&bean不是requiredType的实例if (requiredType != null && !requiredType.isInstance(bean)) {try {// 获取此BeanFactory使用的类型转换器,将bean转换为requiredTypeT convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);// 如果convertedBean为nullif (convertedBean == null) {// 抛出Bean不是必要类型的异常throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());}// 返回convertedBeanreturn 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());}}// 将bean返回出去return (T) bean;}
3、 DefaultSingletonBeanRegistry#getSingleton()
/**
* 返回以给定名称注册的(原始)单例对象,如果尚未注册,则创建并注册一个对象
*/
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {// 如果beanName为null,抛出异常Assert.notNull(beanName, "Bean name must not be null");// 使用单例对象的高速缓存Map作为锁,保证线程同步synchronized (this.singletonObjects) {// 从单例对象的高速缓存Map中获取beanName对应的单例对象Object singletonObject = this.singletonObjects.get(beanName);// 如果单例对象获取不到if (singletonObject == null) {// 如果当前在destorySingletons中if (this.singletonsCurrentlyInDestruction) {throw new BeanCreationNotAllowedException(beanName,"Singleton bean creation not allowed while singletons of this factory are in destruction " +"(Do not request a bean from a BeanFactory in a destroy method implementation!)");}// 如果当前日志级别时调试if (logger.isDebugEnabled()) {logger.debug("Creating shared instance of singleton bean '" + beanName + "'");}// 创建单例之前的回调,默认实现将单例注册为当前正在创建中beforeSingletonCreation(beanName);// 表示生成了新的单例对象的标记,默认为false,表示没有生成新的单例对象boolean newSingleton = false;// 有抑制异常记录标记,没有时为true,否则为falseboolean recordSuppressedExceptions = (this.suppressedExceptions == null);// 如果没有抑制异常记录if (recordSuppressedExceptions) {// 对抑制的异常列表进行实例化(LinkedHashSet)this.suppressedExceptions = new LinkedHashSet<>();}try {// 从单例工厂中获取对象singletonObject = singletonFactory.getObject();// 生成了新的单例对象的标记为true,表示生成了新的单例对象newSingleton = true;}catch (IllegalStateException ex) {// Has the singleton object implicitly appeared in the meantime ->// if yes, proceed with it since the exception indicates that state.// 同时,单例对象是否隐式出现 -> 如果是,请继续操作,因为异常表明该状态// 尝试从单例对象的高速缓存Map中获取beanName的单例对象singletonObject = this.singletonObjects.get(beanName);// 如果获取失败,抛出异常if (singletonObject == null) {throw ex;}}// 捕捉Bean创建异常catch (BeanCreationException ex) {// 如果没有抑制异常记录if (recordSuppressedExceptions) {// 遍历抑制的异常列表for (Exception suppressedException : this.suppressedExceptions) {// 将抑制的异常对象添加到 bean创建异常 中,这样做的,就是相当于 '因XXX异常导致了Bean创建异常‘ 的说法ex.addRelatedCause(suppressedException);}}// 抛出异常throw ex;}finally {// 如果没有抑制异常记录if (recordSuppressedExceptions) {// 将抑制的异常列表置为null,因为suppressedExceptions是对应单个bean的异常记录,置为null// 可防止异常信息的混乱this.suppressedExceptions = null;}// 创建单例后的回调,默认实现将单例标记为不在创建中afterSingletonCreation(beanName);}// 生成了新的单例对象if (newSingleton) {// 将beanName和singletonObject的映射关系添加到该工厂的单例缓存中:addSingleton(beanName, singletonObject);}}// 返回该单例对象return singletonObject;}}