标签:
//根据Bean名称,向容器获取指定名称的Bean public Object getBean(String name) throws BeansException { return getBeanFactory().getBean(name); } //根据Bean名称和类型,向容器获取指定名称和类型的Bean public <T> T getBean(String name, Class<T> requiredType) throws BeansException { return getBeanFactory().getBean(name, requiredType); } //根据Bean的类型,向容器获取指定类型的Bean public <T> T getBean(Class<T> requiredType) throws BeansException { return getBeanFactory().getBean(requiredType); } //根据Bean名称和一些指定参数,向IoC容器获取符合条件的Bean public Object getBean(String name, Object... args) throws BeansException { return getBeanFactory().getBean(name, args); }
public Object getBean(String name) throws BeansException { return doGetBean(name, null, null, false); } public <T> T getBean(String name, Class<T> requiredType) throws BeansException { return doGetBean(name, requiredType, null, false); } public Object getBean(String name, Object... args) throws BeansException { return doGetBean(name, null, args, false); } public <T> T getBean(String name, Class<T> requiredType, Object... args) throws BeansException { return doGetBean(name, requiredType, args, false); } //真正实现向IoC容器获取Bean的功能,也是触发依赖注入功能的地方 @SuppressWarnings("unchecked") protected <T> T doGetBean( final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly) throws BeansException { //根据指定的名称获取被管理Bean的名称,剥离指定名称中对容器的相关依赖如果指定的是别名,将别名转换为规范的Bean名称 final String beanName = transformedBeanName(name); Object bean; //先从缓存中取是否已经有被创建过的单态类型的Bean,对于单态模式的Bean整个IoC容器中只创建一次,不需要重复创建 Object sharedInstance = getSingleton(beanName); //IoC容器创建单态模式Bean实例对象 if (sharedInstance != null && args == null) { if (logger.isDebugEnabled()) { //如果指定名称的Bean在容器中已有单态模式的Bean被创建,直接返回已经创建的Bean if (isSingletonCurrentlyInCreation(beanName)) { logger.debug("Returning eagerly cached instance of singleton bean '" + beanName + "' that is not fully initialized yet - a consequence of a circular reference"); } else { logger.debug("Returning cached instance of singleton bean '" + beanName + "'"); } } //获取给定Bean的实例对象,主要是完成FactoryBean的相关处理 //注意:BeanFactory是管理容器中Bean的工厂,而FactoryBean是创建创建对象的工厂Bean,两者之间有区别 bean = getObjectForBeanInstance(sharedInstance, name, beanName, null); } else {//缓存没有正在创建的单态模式Bean //缓存中已经有已经创建的原型模式Bean,但是由于循环引用的问题导致实例化对象失败 if (isPrototypeCurrentlyInCreation(beanName)) { throw new BeanCurrentlyInCreationException(beanName); } //对IoC容器中是否存在指定名称的BeanDefinition进行检查,首先检查是否能在当前的BeanFactory中获取的所需要的Bean,如果不能则委托当前容器 //的父级容器去查找,如果还是找不到则沿着容器的继承体系向父级容器查找 BeanFactory parentBeanFactory = getParentBeanFactory(); //当前容器的父级容器存在,且当前容器中不存在指定名称的Bean if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { //解析指定Bean名称的原始名称 String nameToLookup = originalBeanName(name); if (args != null) { //委派父级容器根据指定名称和显式的参数查找 return (T) parentBeanFactory.getBean(nameToLookup, args); } else { //委派父级容器根据指定名称和类型查找 return parentBeanFactory.getBean(nameToLookup, requiredType); } } //创建的Bean是否需要进行类型验证,一般不需要 if (!typeCheckOnly) { //向容器标记指定的Bean已经被创建 markBeanAsCreated(beanName); } //根据指定Bean名称获取其父级的Bean定义,主要解决Bean继承时子类合并父类公共属性问题 final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); checkMergedBeanDefinition(mbd, beanName, args); //获取当前Bean所有依赖Bean的名称 String[] dependsOn = mbd.getDependsOn(); //如果当前Bean有依赖Bean if (dependsOn != null) { for (String dependsOnBean : dependsOn) { //递归调用getBean方法,获取当前Bean的依赖Bean getBean(dependsOnBean); //把被依赖Bean注册给当前依赖的Bean registerDependentBean(dependsOnBean, beanName); } } //创建单态模式Bean的实例对象 if (mbd.isSingleton()) { //这里使用了一个匿名内部类,创建Bean实例对象,并且注册给所依赖的对象 sharedInstance = getSingleton(beanName, new ObjectFactory() { public Object getObject() throws BeansException { try { <span style="white-space:pre"> </span>//创建一个指定Bean实例对象,如果有父级继承,则合并子类和父类的定义 return createBean(beanName, mbd, args); } catch (BeansException ex) { //显式地从容器单态模式Bean缓存中清除实例对象 destroySingleton(beanName); throw ex; } } }); //获取给定Bean的实例对象 bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd); } //IoC容器创建原型模式Bean实例对象 else if (mbd.isPrototype()) { //原型模式(Prototype)是每次都会创建一个新的对象 Object prototypeInstance = null; try { <span style="white-space:pre"> </span>//回调beforePrototypeCreation方法,默认的功能是注册当前创建的原型对象 beforePrototypeCreation(beanName); //创建指定Bean对象实例 prototypeInstance = createBean(beanName, mbd, args); } finally { <span style="white-space:pre"> </span>//回调afterPrototypeCreation方法,默认的功能告诉IoC容器指//定Bean的原型对象不再创建了 afterPrototypeCreation(beanName); } //获取给定Bean的实例对象 bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd); } //要创建的Bean既不是单态模式,也不是原型模式,则根据Bean定义资源中的生命周期范围,选择实例化Bean的合适方法,这种在Web应用程序中 <span style="white-space:pre"> </span>//比较常用,如:request、session、application等生命周期 else { String scopeName = mbd.getScope(); final Scope scope = this.scopes.get(scopeName); //Bean定义资源中没有配置生命周期范围,则Bean定义不合法 if (scope == null) { throw new IllegalStateException("No Scope registered for scope '" + scopeName + "'"); } try { //这里又使用了一个匿名内部类,获取一个指定生命周期范围的实例 Object scopedInstance = scope.get(beanName, new ObjectFactory() { public Object getObject() throws BeansException { beforePrototypeCreation(beanName); try { return createBean(beanName, mbd, args); } finally { afterPrototypeCreation(beanName); } } }); //获取给定Bean的实例对象 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); } } } //对创建的Bean实例对象进行类型检查 if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) { throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass()); } return (T) bean; }这里面有几个地方要好好看一下:
protected Object createBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) throws BeanCreationException { if (logger.isDebugEnabled()) { logger.debug("Creating instance of bean '" + beanName + "'"); } //判断需要创建的Bean是否可以实例化,即是否可以通过当前的类加载器加载 resolveBeanClass(mbd, beanName); //校验和准备Bean中的方法覆盖 try { mbd.prepareMethodOverrides(); } catch (BeanDefinitionValidationException ex) { throw new BeanDefinitionStoreException(mbd.getResourceDescription(), beanName, "Validation of method overrides failed", ex); } try { <span style="white-space:pre"> </span>//如果Bean配置了初始化前和初始化后的处理器,则试图返回一个需要创建Bean的代理对象 Object bean = resolveBeforeInstantiation(beanName, mbd); if (bean != null) { return bean; } } catch (Throwable ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "BeanPostProcessor before instantiation of bean failed", ex); } //创建Bean的入口 Object beanInstance = doCreateBean(beanName, mbd, args); if (logger.isDebugEnabled()) { logger.debug("Finished creating instance of bean '" + beanName + "'"); } return beanInstance; }上面的代码只是对Bean进行了一些检测和其他处理,具体的代码还要看doCreateBean()方法。
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) { //封装被创建的Bean对象 BeanWrapper instanceWrapper = null; if (mbd.isSingleton()){//单态模式的Bean,先从容器中缓存中获取同名Bean instanceWrapper = this.factoryBeanInstanceCache.remove(beanName); } if (instanceWrapper == null) { //创建实例对象 instanceWrapper = createBeanInstance(beanName, mbd, args); } final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null); //获取实例化对象的类型 Class beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null); //调用PostProcessor后置处理器 synchronized (mbd.postProcessingLock) { if (!mbd.postProcessed) { applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName); mbd.postProcessed = true; } } // Eagerly cache singletons to be able to resolve circular references //向容器中缓存单态模式的Bean对象,以防循环引用 boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences && isSingletonCurrentlyInCreation(beanName)); if (earlySingletonExposure) { if (logger.isDebugEnabled()) { logger.debug("Eagerly caching bean '" + beanName + "' to allow for resolving potential circular references"); } //这里是一个匿名内部类,为了防止循环引用,尽早持有对象的引用 addSingletonFactory(beanName, new ObjectFactory() { public Object getObject() throws BeansException { return getEarlyBeanReference(beanName, mbd, bean); } }); } //Bean对象的初始化,依赖注入在此触发 //这个exposedObject在初始化完成之后返回作为依赖注入完成后的Bean Object exposedObject = bean; try { //将Bean实例对象封装,并且Bean定义中配置的属性值赋值给实例对象 populateBean(beanName, mbd, instanceWrapper); if (exposedObject != null) { //初始化Bean对象 exposedObject = initializeBean(beanName, exposedObject, mbd); } } catch (Throwable ex) { if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) { throw (BeanCreationException) ex; } else { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex); } } if (earlySingletonExposure) { //获取指定名称的已注册的单态模式Bean对象 Object earlySingletonReference = getSingleton(beanName, false); if (earlySingletonReference != null) { //根据名称获取的以注册的Bean和正在实例化的Bean是同一个 if (exposedObject == bean) { //当前实例化的Bean初始化完成 exposedObject = earlySingletonReference; } //当前Bean依赖其他Bean,并且当发生循环引用时不允许新创建实例对象 else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) { String[] dependentBeans = getDependentBeans(beanName); Set<String> actualDependentBeans = new LinkedHashSet<String>(dependentBeans.length); //获取当前Bean所依赖的其他Bean for (String dependentBean : dependentBeans) { //对依赖Bean进行类型检查 if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) { actualDependentBeans.add(dependentBean); } } if (!actualDependentBeans.isEmpty()) { throw new BeanCurrentlyInCreationException(beanName, "Bean with name '" + beanName + "' has been injected into other beans [" + StringUtils.collectionToCommaDelimitedString(actualDependentBeans) + "] in its raw version as part of a circular reference, but has eventually been " + "wrapped. This means that said other beans do not use the final version of the " + "bean. This is often the result of over-eager type matching - consider using " + "'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example."); } } } } //注册完成依赖注入的Bean try { registerDisposableBeanIfNecessary(beanName, bean, mbd); } catch (BeanDefinitionValidationException ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex); } return exposedObject; }上面的代码有两个关键的地方:createBeanInstance:创建对象的方法;populateBean:完成属性注入,初始化依赖注入等。我们重点关注createBeanInstance方法。
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) { //检查确认Bean是可实例化的 Class beanClass = resolveBeanClass(mbd, beanName); //使用工厂方法对Bean进行实例化 if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Bean class isn't public, and non-public access not allowed: " + beanClass.getName()); } if (mbd.getFactoryMethodName() != null) { //调用工厂方法实例化 return instantiateUsingFactoryMethod(beanName, mbd, args); } //使用容器的自动装配方法进行实例化 boolean resolved = false; boolean autowireNecessary = false; if (args == null) { synchronized (mbd.constructorArgumentLock) { if (mbd.resolvedConstructorOrFactoryMethod != null) { resolved = true; autowireNecessary = mbd.constructorArgumentsResolved; } } } if (resolved) { if (autowireNecessary) { //配置了自动装配属性,使用容器的自动装配实例化容器的自动装配是根据参数类型匹配Bean的构造方法 return autowireConstructor(beanName, mbd, null, null); } else { //使用默认的无参构造方法实例化 return instantiateBean(beanName, mbd); } } //使用Bean的构造方法进行实例化 Constructor[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName); if (ctors != null || mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR || mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) { //使用容器的自动装配特性,调用匹配的构造方法实例化 return autowireConstructor(beanName, mbd, ctors, args); } //使用默认的无参构造方法实例化 return instantiateBean(beanName, mbd); } //使用默认的无参构造方法实例化Bean对象 protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) { try { Object beanInstance; final BeanFactory parent = this; //获取系统的安全管理接口,JDK标准的安全管理API if (System.getSecurityManager() != null) { //这里是一个匿名内置类,根据实例化策略创建实例对象 beanInstance = AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { return getInstantiationStrategy().instantiate(mbd, beanName, parent); } }, getAccessControlContext()); } else { //将实例化的对象封装起来 beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent); } BeanWrapper bw = new BeanWrapperImpl(beanInstance); initBeanWrapper(bw); return bw; } catch (Throwable ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex); } }上面的代码我们可以看到,对于通过工厂方法和自动装配的Bean的实例化比较清晰,调用具体的工厂方法和参数匹配构造方法就可完成对象的创建(具体的方法不
public Object instantiate(RootBeanDefinition beanDefinition, String beanName, BeanFactory owner) { //如果Bean定义中没有方法覆盖,则就不需要CGLIB父类类的方法 if (beanDefinition.getMethodOverrides().isEmpty()) { Constructor<?> constructorToUse; synchronized (beanDefinition.constructorArgumentLock) { //获取对象的构造方法或工厂方法 constructorToUse = (Constructor<?>) beanDefinition.resolvedConstructorOrFactoryMethod; //如果没有构造方法且没有工厂方法 if (constructorToUse == null) { //使用JDK的反射机制,判断要实例化的Bean是否是接口 final Class clazz = beanDefinition.getBeanClass(); if (clazz.isInterface()) { throw new BeanInstantiationException(clazz, "Specified class is an interface"); } try { if (System.getSecurityManager() != null) { //这里是一个匿名内置类,使用反射机制获取Bean的构造方法 constructorToUse = AccessController.doPrivileged(new PrivilegedExceptionAction<Constructor>() { public Constructor run() throws Exception { return clazz.getDeclaredConstructor((Class[]) null); } }); } else { constructorToUse = clazz.getDeclaredConstructor((Class[]) null); } beanDefinition.resolvedConstructorOrFactoryMethod = constructorToUse; } catch (Exception ex) { throw new BeanInstantiationException(clazz, "No default constructor found", ex); } } } <span style="white-space:pre"> </span> //使用BeanUtils实例化,通过反射机制调用”构造方法.newInstance(arg)”来进行实例化 return BeanUtils.instantiateClass(constructorToUse); } else { //使用CGLIB来实例化对象 return instantiateWithMethodInjection(beanDefinition, beanName, owner); } }在这里我们可以看到,是通过是否有方法替换来决定是采用反射还算采用CGLIB方法实例对象。这里我要多一点:beanDefinition.getMethodOverrides()这个地方取到的值是我们在解析BeanDefinition的lookup-method和replace-method,忘记的同学可以返回到BeanDefinitionParserDelegate类的parseBeanDefinitionElement方法中查看parseLookupOverrideSubElements(ele, bd.getMethodOverrides())和parseReplacedMethodSubElements(ele, bd.getMethodOverrides())子方法。也就是说,如果bean中有配置这两个属性,我们就采取cglib方法创建对象,如果没有,就采用无参构造器方法创建对象。具体的创建方法,大家具体去看下,我目前还不是能说的太明白。
<lookup-method bean=”原型bean的id” name=”方法名称”/>
<replaced-method name=”被替换的方法” replacer=”替换类,该类必须实现MethodReplacer接口”> <arg-type></arg-type>//如果这个被替换的方法被重载了,那么必须写arg-type </replaced-method><arg-type match=”String”></arg-type>,这样才会被解析成一个为String类型的参数,而<arg-type>String</arg-type>这样只会被解析成拦截只有一个参数的某方法。
【Spring源码--IOC容器的实现】(五)Bean对象的创建
标签:
原文地址:http://blog.csdn.net/u013185616/article/details/52279363