首页 > 代码库 > SpringMVC 源代码深度解析 IOC容器(Bean实例化和依赖注入)
SpringMVC 源代码深度解析 IOC容器(Bean实例化和依赖注入)
SpringMVC最核心的IOC的控制反转,动态的向某个对象提供它所需要的其他对象,例如:对象A时,需要对象B时,这时不像以前我们之前要在A对象里实例化B对象,这时B对象的实例化由IOC容器会主动创建一个对象B然后注入到对象A里,提供使用。我们项目开发中,最经常用到,那怎么实现实例Bean并依赖注入呢?我们今天带着这些问题来通过SpringMVC源代码进行深入的解析。这篇介绍不对注解实例化和注入进行讲解,这个放在后面在介绍。
我们平常写的一个类,并依赖调用了类的某个方法,这时需要依赖那个类已经实例化,这样才能调用,这些都是交给IOC控制反转,这是我们写的一个类,代码如下
package cn.test.service.impl; import cn.test.service.TestService2; public class TestServiceImpl2 implements TestService2{ }
package cn.test.service.impl; import cn.test.service.TestService; import cn.test.service.TestService2; public class TestServiceImpl implements TestService{ private TestServiceImpl(){ System.out.println("xx"); } private TestService2 testService2; public TestService2 getTestService2() { return testService2; } public void setTestService2(TestService2 testService2) { this.testService2 = testService2; } }
在配置文件配置了对应的Bean
<span style="font-size:18px;"> <bean id="testService" class="cn.test.service.impl.TestServiceImpl" > <property name="testService2" ref="testService2"></property> </bean> <bean id="testService2" class="cn.test.service.impl.TestServiceImpl2" ></bean></span>那SpringMVC 怎么实现实例Bean并依赖注入?我们带着上面实现的代码来解析。
首先我们先回到refresh这个方法,在上一篇Bean解析和注册,大家应该还记得吧,里面有postProcessBeanFactory这个方法,就是实例化bean的,我们带着好奇心来分析了解。当Bean定义资源被载入IoC容器之后,容器将Bean定义资源解析为容器内部的数据结构,然后BeanDefinition注册到容器中,AbstractApplicationContext类中的finishBeanFactoryInitialization方法对配置了属性的Bean进行初始化过程,源码如下:
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) { // CONVERSION_SERVICE_BEAN_NAME为转换服务(ConversionService) 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)); } // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early. 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. beanFactory.freezeConfiguration(); // 对bean进行实例化 <span style="color:#ff0000;">beanFactory.preInstantiateSingletons();</span> }
preInstantiateSingletons由对bean进行实例化由子类DefaultListableBeanFactory来实现的。源代码:
public void preInstantiateSingletons() throws BeansException { if (this.logger.isInfoEnabled()) { this.logger.info("Pre-instantiating singletons in " + this); } List<String> beanNames; synchronized (this.beanDefinitionMap) { // 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. beanNames = new ArrayList<String>(this.beanDefinitionNames); } for (String beanName : beanNames) { RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName); if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) { if (isFactoryBean(beanName)) { final FactoryBean<?> factory = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName); boolean isEagerInit; if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) { isEagerInit = AccessController.doPrivileged(new PrivilegedAction<Boolean>() { public Boolean run() { return ((SmartFactoryBean<?>) factory).isEagerInit(); } }, getAccessControlContext()); } else { isEagerInit = (factory instanceof SmartFactoryBean && ((SmartFactoryBean<?>) factory).isEagerInit()); } if (isEagerInit) { getBean(beanName); } } else { <span style="color:#cc0000;">getBean(beanName);</span> } } } }
getBean(beanName);对bean进行实例化并对属性依赖进行注入过程。前面解析的代码不重要,主要是入口点,接下来才是重点, 创建bean时,如果缓存中有单例Bean时,就从缓存获取,如果没有就新建,通过匿名的内部类来创建Bean时根据Bean的作用域来创建的,有单实例作用域、原型作用域、Request等。源代码如下:
public Object getBean(String name) throws BeansException { return doGetBean(name, null, null, false); } @SuppressWarnings("unchecked") protected <T> T doGetBean( final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly) throws BeansException { //如果指定的是别名,将别名转换为规范的Bean名称 final String beanName = transformedBeanName(name); Object bean; // 如果缓存中有单例Bean时,就从缓存获取 Object sharedInstance = getSingleton(beanName); if (sharedInstance != null && args == null) { if (logger.isDebugEnabled()) { 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 = 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); } // 获取父工厂 BeanFactory parentBeanFactory = getParentBeanFactory(); //检查BeanDefinition是否有当前的BeanFactory,如果没有,就到父工厂去查找 if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { // Not found -> check parent. String nameToLookup = originalBeanName(name); if (args != null) { // Delegation to parent with explicit args. return (T) parentBeanFactory.getBean(nameToLookup, args); } else { // No args -> delegate to standard getBean method. return parentBeanFactory.getBean(nameToLookup, requiredType); } } if (!typeCheckOnly) { markBeanAsCreated(beanName); } try { //看说明(2) final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); //是否为抽象的、是否Prototype checkMergedBeanDefinition(mbd, beanName, args); // 获取当前Bean所有依赖Bean的名称 String[] dependsOn = mbd.getDependsOn(); if (dependsOn != null) { for (String dependsOnBean : dependsOn) { //递归调用getBean方法 getBean(dependsOnBean); //注册依赖的bean registerDependentBean(dependsOnBean, beanName); } } // 创建单例bean实例 if (mbd.isSingleton()) { //内部类,实现创建bean sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() { public Object getObject() throws BeansException { try { //创建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. destroySingleton(beanName); throw ex; } } }); //获取bean实例对象 bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd); } //是否为原型bean 每次我们从容器中调用bean时,都返回一个新的实例 else if (mbd.isPrototype()) { // 原型bean都会创建一个新的出来 Object prototypeInstance = null; try { //注册新bean beforePrototypeCreation(beanName); //创建新的bean实例对象 prototypeInstance = createBean(beanName, mbd, args); } finally { afterPrototypeCreation(beanName); } //获取bean对象 bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd); } else { //创建Bean作用域类型 request、session、globalSession,通过Scope接口定义新的作用域 String scopeName = mbd.getScope(); final Scope scope = this.scopes.get(scopeName); if (scope == null) { throw new IllegalStateException("No Scope registered for scope '" + scopeName + "'"); } try { Object scopedInstance = scope.get(beanName, new ObjectFactory<Object>() { public Object getObject() throws BeansException { 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 && bean != null && !requiredType.isAssignableFrom(bean.getClass())) { try { return getTypeConverter().convertIfNecessary(bean, requiredType); } catch (TypeMismatchException ex) { if (logger.isDebugEnabled()) { logger.debug("Failed to convert bean '" + name + "' to required type [" + ClassUtils.getQualifiedName(requiredType) + "]", ex); } throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass()); } } return (T) bean; }
我们解析到这边,对前面的思路在整理一下,这样我们到后面就比较不会那么模糊
总结:(1)先List<String> beanDefinitionNames获取BeanName,然后通过BeanName 获取Map<String, RootBeanDefinition>RootBeanDefinition,然后判断是否 为单例、不是抽象、是为Lazy-init=false 然后调用getBean方法。我们在配置中可以定义父Bean和子bean,父Bean用RootBeanDefinition 表示,子Bean 用ChildBeanDefinition表示,而没有父Bean用RootBeanDefinition 表示。如图所示:
(2)如果BeanName是别名,先转换为原来的BeanName不是别名,然后如果缓存中有单例Bean时,就从缓存获取,如果没有的话,就创建一个
(3)先检查是否父工厂存在,如果有的话,获取父工厂
(4)判断Bean依赖对象所有的名称,如果有的话,获取依赖对象的名称,然后循环getBean();
(5)检查Bean的作用域,Scope 作用域、原型作用域、Request等,来实例化Bean ,是由FactoryBean是创建创建对象的工厂Bean,通过调用这个对象 的 getObject 方法就能获取用户自定义产生的对象,从而为 Spring 提供了很好的扩展性。Spring 获取 FactoryBean 本身的对象是在前面加上 & 来完成 的。
现在思路就比较清晰了,接下来我们来解析具体实现创建Bean实例化的类。
接下来我们来继续分析具体的创建过程createBean(beanName, mbd, args);这个方法,是由AbstractAutowireCapableBeanFactory来实现的,AbstractAutowireCapableBeanFactory我们来看看它的继承关系,之前就有总体的继承关系,我们这边在温习一下,如图所示:
createBean(beanName, mbd, args);这个方法,源代码如下:
@Override protected Object createBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) throws BeanCreationException { if (logger.isDebugEnabled()) { logger.debug("Creating instance of bean '" + beanName + "'"); } // Make sure bean class is actually resolved at this point. resolveBeanClass(mbd, beanName); // Prepare method overrides. try { mbd.prepareMethodOverrides(); } catch (BeanDefinitionValidationException ex) { throw new BeanDefinitionStoreException(mbd.getResourceDescription(), beanName, "Validation of method overrides failed", ex); } try { // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance. 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); } Object beanInstance = <span style="color:#cc0000;">doCreateBean(beanName, mbd, args);</span> 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()) { //根据beanName从容器中获取 instanceWrapper = this.factoryBeanInstanceCache.remove(beanName); } if (instanceWrapper == null) { //创建 instanceWrapper = <span style="color:#ff0000;">createBeanInstance(beanName, mbd, args);</span> } //获取bean的实例化 final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null); //bean的类型 Class<?> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null); // Allow post-processors to modify the merged bean definition. synchronized (mbd.postProcessingLock) { if (!mbd.postProcessed) { applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName); mbd.postProcessed = true; } } 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"); } //向容器中缓存单态实例的Bean对象,以防循环实例化 addSingletonFactory(beanName, new ObjectFactory<Object>() { public Object getObject() throws BeansException { return getEarlyBeanReference(beanName, mbd, bean); } }); } // Initialize the bean instance. Object exposedObject = bean; try { //设置bean实例的属性,如果属性需要注入的bean实例,则把bean实例对象封装好依赖注入 <span style="color:#ff0000;">populateBean(beanName, mbd, instanceWrapper);</span> 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) { if (exposedObject == bean) { exposedObject = earlySingletonReference; } else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) { String[] dependentBeans = getDependentBeans(beanName); Set<String> actualDependentBeans = new LinkedHashSet<String>(dependentBeans.length); for (String dependentBean : dependentBeans) { 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."); } } } } // Register bean as disposable. try { registerDisposableBeanIfNecessary(beanName, bean, mbd); } catch (BeanDefinitionValidationException ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex); } return exposedObject; }
我们对这个方法在总结一下:
(1)封装Bean,用 BeanWrapper是对Bean的包装,其接口中所定义的功能很简单包括设置获取被包装的对象,获取被包装bean的属性描述器,由于BeanWrapper接口是PropertyAccessor的子接口,因此其也可以设置以及访问被包装对象的属性值。BeanWrapper大部分情况下是在IOC内部进行使用,通过BeanWrapper,IOC容器可以用统一的方式来访问Bean的属性。上一篇转载的有介绍BeanWrapper,这里就不具体介绍了。
(2)根据BeanName去容器缓存中获取已经Bean的包装好的BeanWrapper,如果没有就调用createBeanInstance(beanName, mbd, args),实例化Bean
(3)获取Bean的类型,这个类型是什么,如图所示:
(4)获取BeanWrapper里已经实例好的Bean,然后放到缓存,这样下次已经有了,就不用在创建。
(5)设置Bean实例的属性,对需要转换的属性进行转换,例如数组等,如果属性是引用类型,如果引用Bean没实例化,要在实例化,把bean实例对象封装好依赖注入在注入进来。
这里面有两个重要的实现方法createBeanInstance(beanName, mbd, args);和populateBean(beanName, mbd, instanceWrapper);createBeanInstance是创建bean实例的,populateBean设置属性的,如果属性的是对象,需要把依赖的对象创建好,设置实例化对象。这两个方法也是重点。
第一个:我们来分析createBeanInstance的方法,这里有介绍了注解的实例化,我们后面章节在介绍。可以带有参数构造函数或者默认无参的构造函数、还有工厂方法来创建Bean的实例,源代码如下:
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) { // 确实bean是否能实例化 Class<?> beanClass = resolveBeanClass(mbd, beanName); 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) { // //使用工厂方法实例化bean return instantiateUsingFactoryMethod(beanName, mbd, args); } // Shortcut when re-creating the same bean... 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) { return autowireConstructor(beanName, mbd, null, null); } else { //实例化bean return <span style="color:#990000;">instantiateBean(beanName, mbd)</span>; } } // Need to determine the constructor... 、、 Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName); if (ctors != null || mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR || mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) { return autowireConstructor(beanName, mbd, ctors, args); } // No special handling: simply use no-arg constructor. return instantiateBean(beanName, mbd); }
instantiateBean默认是实例化无参的构造函数的。
protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) { try { Object beanInstance; final BeanFactory parent = this; if (System.getSecurityManager() != null) { beanInstance = AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { return getInstantiationStrategy().instantiate(mbd, beanName, parent); } }, getAccessControlContext()); } else { beanInstance = <span style="color:#cc0000;">getInstantiationStrategy().instantiate(mbd, beanName, parent);</span> } BeanWrapper bw = new BeanWrapperImpl(beanInstance); initBeanWrapper(bw); return bw; } catch (Throwable ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex); } }
getInstantiationStrategy().instantiate(mbd, beanName, parent);是由InstantiationStrategy的子类SimpleInstantiationStrategy来实现的,关系如图所示:
为了方便我们采用不同的实例化策略,以满足不同应用的需求,可以用CGLib类库来动态的创建Bean实例或者JDK反射机制来实现的,在子类中生成方法注入的逻辑,然后使用这个动态生成的子类创建bean的实例,这个实例化过程是没有对bean进行设置属性的,是有BeanWrapper 来设置的。具体由instantiate实现的,这里面说明了,如果方法有被覆盖,用JDK反射机制来实例化,否则用CGLib类库来动态的创建Bean实例,这里用beanDefinition.resolvedConstructorOrFactoryMethod来判断的。源代码如下:
public Object instantiate(RootBeanDefinition beanDefinition, String beanName, BeanFactory owner) { // Don't override the class with CGLIB if no overrides. if (beanDefinition.getMethodOverrides().isEmpty()) { Constructor<?> constructorToUse; synchronized (beanDefinition.constructorArgumentLock) { constructorToUse = (Constructor<?>) beanDefinition.resolvedConstructorOrFactoryMethod; if (constructorToUse == null) { final Class<?> clazz = beanDefinition.getBeanClass(); if (clazz.isInterface()) { throw new BeanInstantiationException(clazz, "Specified class is an interface"); } try { //用java反射机制来实例化bean if (System.getSecurityManager() != null) { 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); } } } return BeanUtils.instantiateClass(constructorToUse); } else { // Must generate CGLIB subclass. //用CGLIB 来动态创建bean return instantiateWithMethodInjection(beanDefinition, beanName, owner); } }
SimpleInstantiationStrategy,如果方法有被覆盖,用JDK反射机制来实例化,否则用CGLib类库来动态的创建Bean实例。这里CGLib类继承,如图所示:
这里我们来验证一下如果方法有被覆盖,用JDK反射机制来实例化,否则用CGLib类库来动态的创建Bean实例,还记得我们最开始的TestServiceImpl这个类,并在配置文件配置了Bean,在实例化肯定是使用了,JDK反射机制来实例化,因为它类还有依赖了TestServiceImpl2这个类,我们跟踪代码证实一下:
我们这边有写了一个无参的构造函数,并且有实例化,然后我们继续跟踪是采用什么实例化,如图所示:
经过我们验证是正确的。
第二个:实例化就讲到这里,接下去我们继续解析Bean属性的注入。
实现的方法是populateBean这个方法,应该还记得吧。doCreateBean();方法里面的。
protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) { <span style="color:#cc0000;">PropertyValues pvs = mbd.getPropertyValues(); </span> if (bw == null) { if (!pvs.isEmpty()) { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance"); } else { // Skip property population phase for null instance. return; } } // Give any InstantiationAwareBeanPostProcessors the opportunity to modify the // state of the bean before properties are set. This can be used, for example, // to support styles of field injection. boolean continueWithPropertyPopulation = true; if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof InstantiationAwareBeanPostProcessor) { InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) { continueWithPropertyPopulation = false; break; } } } } if (!continueWithPropertyPopulation) { return; } if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME || mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) { MutablePropertyValues newPvs = new MutablePropertyValues(pvs); // Add property values based on autowire by name if applicable. if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) { autowireByName(beanName, mbd, bw, newPvs); } // Add property values based on autowire by type if applicable. if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) { autowireByType(beanName, mbd, bw, newPvs); } pvs = newPvs; } boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors(); boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE); if (hasInstAwareBpps || needsDepCheck) { PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching); if (hasInstAwareBpps) { for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof InstantiationAwareBeanPostProcessor) { InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; ///使用BeanPostProcessor处理器处理属性值 pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName); if (pvs == null) { return; } } } } if (needsDepCheck) { checkDependencies(beanName, mbd, filteredPds, pvs); } } //对属性的注入 <span style="color:#ff0000;">applyPropertyValues(beanName, mbd, bw, pvs);</span> }先获取PropertyValues 就是获取Bean配置里面属性的值,然后调用applyPropertyValues这个方法,applyPropertyValues方法的源代码如下:
protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) { if (pvs == null || pvs.isEmpty()) { return; } MutablePropertyValues mpvs = null; List<PropertyValue> original; if (System.getSecurityManager() != null) { if (bw instanceof BeanWrapperImpl) { ((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext()); } } //对属性进行循环 if (pvs instanceof MutablePropertyValues) { mpvs = (MutablePropertyValues) pvs; if (mpvs.isConverted()) { // Shortcut: use the pre-converted values as-is. try { bw.setPropertyValues(mpvs); return; } catch (BeansException ex) { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Error setting property values", ex); } } original = mpvs.getPropertyValueList(); } else { //获取了<property name="testService2" ref="testService2"></property>里面的ref值或者value original = Arrays.asList(pvs.getPropertyValues()); } //获取用户自定义的类型转换 TypeConverter converter = getCustomTypeConverter(); if (converter == null) { converter = bw; } //实现了一个BeanDefinition的解析实例 BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter); //对属性值进行复制 List<PropertyValue> deepCopy = new ArrayList<PropertyValue>(original.size()); boolean resolveNecessary = false; for (PropertyValue pv : original) { //是否要转换 if (pv.isConverted()) { deepCopy.add(pv); } else { //获取名称 String propertyName = pv.getName(); //获取值 Object originalValue = http://www.mamicode.com/pv.getValue();>总结:(1)对属性进行循环,然后获取属性值
(2)获取用户自定义的类型转换
(3)实现了一个BeanDefinition的解析实例的BeanDefinitionValueResolver,我们来看一个这个类的属性,有保存用户自定义的转换类型、还有保存BeanDefinition
(4)对属性值进行复制,如图所示:
(5)在(3)实例化了一个BeanDefinition解析实例的BeanDefinitionValueResolver对象,通过这个对象调用对具体实现了解析属性值进行解析,并对属性值进行转换。转换类型有对象引用、对集合数组类型的属性解析等。如果对引用对象进行解析时,调用了getBean()方法。
接下来我们来解析属性的具体解析,是由BeanDefinitionValueResolver类实现的,具体实现了解析属性值进行解析,并对属性值进行转换。
resolveValueIfNecessary方法源代码如下:
ublic Object resolveValueIfNecessary(Object argName, Object value) { // 对引用的类型进行转换 // to another bean to be resolved. if (value instanceof RuntimeBeanReference) { RuntimeBeanReference ref = (RuntimeBeanReference) value; return resolveReference(argName, ref); } else if (value instanceof RuntimeBeanNameReference) { String refName = ((RuntimeBeanNameReference) value).getBeanName(); refName = String.valueOf(evaluate(refName)); if (!this.beanFactory.containsBean(refName)) { throw new BeanDefinitionStoreException( "Invalid bean name '" + refName + "' in bean reference for " + argName); } return refName; } else if (value instanceof BeanDefinitionHolder) { // Resolve BeanDefinitionHolder: contains BeanDefinition with name and aliases. BeanDefinitionHolder bdHolder = (BeanDefinitionHolder) value; return resolveInnerBean(argName, bdHolder.getBeanName(), bdHolder.getBeanDefinition()); } else if (value instanceof BeanDefinition) { // Resolve plain BeanDefinition, without contained name: use dummy name. BeanDefinition bd = (BeanDefinition) value; return resolveInnerBean(argName, "(inner bean)", bd); } //对集合数组类型的属性解析 else if (value instanceof ManagedArray) { // May need to resolve contained runtime references. ManagedArray array = (ManagedArray) value; Class<?> elementType = array.resolvedElementType; if (elementType == null) { String elementTypeName = array.getElementTypeName(); if (StringUtils.hasText(elementTypeName)) { try { elementType = ClassUtils.forName(elementTypeName, this.beanFactory.getBeanClassLoader()); array.resolvedElementType = elementType; } catch (Throwable ex) { // Improve the message by showing the context. throw new BeanCreationException( this.beanDefinition.getResourceDescription(), this.beanName, "Error resolving array type for " + argName, ex); } } else { elementType = Object.class; } } return resolveManagedArray(argName, (List<?>) value, elementType); } else if (value instanceof ManagedList) { // May need to resolve contained runtime references. return resolveManagedList(argName, (List<?>) value); } else if (value instanceof ManagedSet) { // May need to resolve contained runtime references. return resolveManagedSet(argName, (Set<?>) value); } else if (value instanceof ManagedMap) { // May need to resolve contained runtime references. return resolveManagedMap(argName, (Map<?, ?>) value); } else if (value instanceof ManagedProperties) { Properties original = (Properties) value; Properties copy = new Properties(); for (Map.Entry propEntry : original.entrySet()) { Object propKey = propEntry.getKey(); Object propValue = http://www.mamicode.com/propEntry.getValue();>这里我们来验证一下我们解析是否正确,还记得我们最开始的TestServiceImpl这个类,并在配置文件配置了Bean,它类还有依赖了TestServiceImpl2这个类,在配置文件
<bean id="testService" class="cn.test.service.impl.TestServiceImpl" > <property name="testService2" ref="testService2"></property></bean>,在属性注入时,类型转换肯定是引用类型。我们来跟踪一下代码,如图所示:
是走引用类型路线,这时会调用genBean(),进行对引用类进行实例化,这都是交给IOC容器实现的,如图所示:
这时已经实例化好了,接下来就是注入进来,如图所示:
我们对Bean的实例化和属性解析并进行类型转换,例如依赖注入。
我们这里总结整个思路:
(1)先List<String> beanDefinitionNames获取BeanName,然后通过BeanName 获取Map<String, RootBeanDefinition> RootBeanDefinition,然后判断是否为单例、不是抽象、是为Lazy-init=false 然后调用getBean方法。
(2)如果BeanName是别名,先转换为原来的BeanName不是别名,然后如果缓存中有单例Bean时,就从缓存获取,如果没有的话,就创建一个
(3)先检查是否父工厂存在,如果有的话,获取父工厂
(4)判断Bean依赖对象所有的名称,如果有的话,获取依赖对象的名称,然后循环getBean();
(5)检查Bean的作用域,Scope 作用域、原型作用域、Request等,来实例化Bean ,是由FactoryBean是创建创建对象的工厂Bean,通过调用这个对象的 getObject 方法就能获取用户自定义产生的对象,从而为 Spring 提供了很好的扩展性。Spring 获取 FactoryBean 本身的对象是在前面加上 & 来完成的。
(6)封装Bean,用 BeanWrapper是对Bean的包装,其接口中所定义的功能很简单包括设置获取被包装的对象,获取被包装bean的属性描述器,由于BeanWrapper接口是PropertyAccessor的子接口,因此其也可以设置以及访问被包装对象的属性值。BeanWrapper大部分情况下是在IOC内部进行使用,通过BeanWrapper,IOC容器可以用统一的方式来访问Bean的属性。
(7)根据BeanName去容器缓存中获取已经Bean的包装好的BeanWrapper,如果没有就调用createBeanInstance(beanName, mbd, args),实例化Bean
(8)获取BeanWrapper里已经实例好的Bean,然后放到缓存,这样下次已经有了,就不用在创建。
(9)设置Bean实例的属性,对需要转换的属性进行转换,例如数组等,如果属性是引用类型,如果引用Bean没实例化,要在实例化,把bean实例对象封装好依赖注入在注入进来。
我这边介绍的主要是配置文件的xml中的配置bean。对注解的@Autowire,@Service@Controller等怎么实例化,和依赖注入等怎么使用,我们在SpringMVC中大部分都是用注解来开发,方便我们使用。我们带着这些问题,下一篇继续解析。
SpringMVC 源代码深度解析 IOC容器(Bean实例化和依赖注入)