以XmlBeanFactory为例,最简单的取bean方式是:
BeanFactory factory = new XmlBeanFactory(new FileSystemResource("D:\\workspace\\JavaApplication2\\src\\javaapplication2\\spring\\beans.xml")); Car obj = (Car)factory.getBean("car");
Bean的配置文件内容也很简单:
<bean id="vehicle" abstract="true"> <property name="wheel" value="Four wheeler"/> </bean> <bean id="car" class="javaapplication2.spring.Car" parent="vehicle"> <property name="dicky" value="Flat dicky"/> </bean>
先看起始点,载入先走AbstractBeanFactory
public Object getBean(String name) throws BeansException { return doGetBean(name, null, null, false); }
doGetBean方法中:
// Create bean instance. if (mbd.isSingleton()) { //传入一个内联类ObjectFactory并实现了getObject方法。 sharedInstance = getSingleton(beanName, new ObjectFactory() { public Object getObject() throws BeansException { 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); //有异常则销毁bean throw ex; } } }); bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd); //此处开始实例化bean
}
通过new ObjectFactory()的回调方法,回调当前类继承的createBean方法,该方法在父类AbstractAutowireCapableBeanFactory中:
AbstractAutowireCapableBeanFactory->
protected Object createBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) throws BeanCreationException { // Make sure bean class is actually resolved at this point. resolveBeanClass(mbd, beanName); //载入该bean的class,并放置到mbd里面,bean的生成不在这里。 // 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); //尝试获取一个proxy,普通bean这里一般是空的返回 if (bean != null) { return bean; } } catch (Throwable ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "BeanPostProcessor before instantiation of bean failed", ex); } Object beanInstance = doCreateBean(beanName, mbd, args); //开始create bean的实例,mbd中包括了需要的class if (logger.isDebugEnabled()) { logger.debug("Finished creating instance of bean '" + beanName + "'"); } return beanInstance; }
进入AbstractBeanFactory中的protected Class resolveBeanClass方法:
try { if (mbd.hasBeanClass()) { return mbd.getBeanClass(); } if (System.getSecurityManager() != null) { return AccessController.doPrivileged(new PrivilegedExceptionAction<Class>() { public Class run() throws Exception { return doResolveBeanClass(mbd, typesToMatch); } }, getAccessControlContext()); } else { return doResolveBeanClass(mbd, typesToMatch); <---还要继续进去看生成方法。 } }
转入doResolveBeanClass:
private Class doResolveBeanClass(RootBeanDefinition mbd, Class... typesToMatch) throws ClassNotFoundException { if (!ObjectUtils.isEmpty(typesToMatch)) { ClassLoader tempClassLoader = getTempClassLoader(); if (tempClassLoader != null) { if (tempClassLoader instanceof DecoratingClassLoader) { DecoratingClassLoader dcl = (DecoratingClassLoader) tempClassLoader; for (Class<?> typeToMatch : typesToMatch) { dcl.excludeClass(typeToMatch.getName()) } } String className = mbd.getBeanClassName(); return (className != null ? ClassUtils.forName(className, tempClassLoader) : null); //通过自己的ClassUtils的forName方法来实例化class } } return mbd.resolveBeanClass(getBeanClassLoader()); <----这里传入了bean的classloader,下面继续看这里 }
AbstractBeanDefinition->resolveBeanClass
public Class resolveBeanClass(ClassLoader classLoader) throws ClassNotFoundException { String className = getBeanClassName(); if (className == null) { return null; } Class resolvedClass = ClassUtils.forName(className, classLoader);//classloader传入后,仍然是用forName方法加载class this.beanClass = resolvedClass; return resolvedClass; }
再来看forName做了些什么
ClassUtils ->
ClassLoader classLoaderToUse = classLoader; if (classLoaderToUse == null) { classLoaderToUse = getDefaultClassLoader(); } try { return classLoaderToUse.loadClass(name); //也比较简单,直接调用loadClass方法加载 }
最终将class load进来。
Bean实例化过程:
AbstractAutowireCapableBeanFactory->createBeanInstance
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) // 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); //这里实例化
进入
AbstractAutowireCapableBeanFactory->instantiateBean
protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) ...这里省略没用的 else { beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);//下面看这里的实例化 } BeanWrapper bw = new BeanWrapperImpl(beanInstance); //返回一个包装类对象 initBeanWrapper(bw); return bw;
SimpleInstantiationStrategy->instantiate
public Object instantiate(RootBeanDefinition beanDefinition, String beanName, BeanFactory owner) synchronized (beanDefinition.constructorArgumentLock) { constructorToUse = (Constructor<?>) beanDefinition.resolvedConstructorOrFactoryMethod; ... } return BeanUtils.instantiateClass(constructorToUse); //BeanUtils来初始化实例 ,给出了实例化需要的构造函数
再来看BeanUtils的实例化方法,比较简单,直接用反射的构造函数来newInstance。
BeanUtils->
public static <T> T instantiateClass(Constructor<T> ctor, Object... args) throws BeanInstantiationException { try { ReflectionUtils.makeAccessible(ctor); return ctor.newInstance(args); }
AbstractAutowireCapableBeanFactory->
Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) // Initialize the bean instance. Object exposedObject = bean; try { populateBean(beanName, mbd, instanceWrapper); if (exposedObject != null) { exposedObject = initializeBean(beanName, exposedObject, mbd); } } return exposedObject; //返回给AbstractBeanFactory