<T>TadaptBeanInstance(String name,Object bean,@NullableClass<?> requiredType){// Check if required type matches the type of the actual bean instance.// 类型不满足的时候,进行下面的逻辑if(requiredType !=null&&!requiredType.isInstance(bean)){try{// 类型转化成功的时候,才会返回Bean,否则抛异常Object convertedBean =getTypeConverter().convertIfNecessary(bean, requiredType);if(convertedBean ==null){thrownewBeanNotOfRequiredTypeException(name, requiredType, bean.getClass());}return(T) convertedBean;}catch(TypeMismatchException ex){if(logger.isTraceEnabled()){
logger.trace("Failed to convert bean '"+ name +"' to required type '"+ClassUtils.getQualifiedName(requiredType)+"'", ex);}thrownewBeanNotOfRequiredTypeException(name, requiredType, bean.getClass());}}// 类型满足,直接返回Beanreturn(T) bean;}
获取单例Bean的方法getSingleton源码分析
publicObjectgetSingleton(String beanName,ObjectFactory<?> singletonFactory){// beanName为空,抛异常Assert.notNull(beanName,"Bean name must not be null");synchronized(this.singletonObjects){// 从单例池获取Object singletonObject =this.singletonObjects.get(beanName);if(singletonObject ==null){// 没有获取到的逻辑// Bean被销毁,抛异常if(this.singletonsCurrentlyInDestruction){thrownewBeanCreationNotAllowedException(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);// 新的单例的标志为Falseboolean newSingleton =false;// 获取排除标志boolean recordSuppressedExceptions =(this.suppressedExceptions ==null);// 排除标志为null的时候,设置这个标志不为null:标明执行开始了if(recordSuppressedExceptions){this.suppressedExceptions =newLinkedHashSet<>();}try{// 调用上面的lambda去真正的创建Bean
singletonObject = singletonFactory.getObject();// 创建Bean成功
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.
singletonObject =this.singletonObjects.get(beanName);if(singletonObject ==null){throw ex;}}catch(BeanCreationException ex){if(recordSuppressedExceptions){for(Exception suppressedException :this.suppressedExceptions){
ex.addRelatedCause(suppressedException);}}throw ex;}finally{// 将排除的标志变为null:标明执行完成了if(recordSuppressedExceptions){this.suppressedExceptions =null;}// 循环依赖一级缓存中放入afterSingletonCreation(beanName);}// 添加到单例池if(newSingleton){addSingleton(beanName, singletonObject);}}// 返回得到的单例Beanreturn singletonObject;}}