一:原理java
當bean是單例時,從緩存獲取單例bean;若是沒有,則建立單例bean,建立單例bean時用反射獲取bean的構造器,經過構造器實例化bean,而後在組裝bean,組裝bean的時候進行依賴注入;以後把單例bean放入緩存中,無需二次建立。spring
當bean是多例時,建立過程與單例建立一致,可是不會放在緩存中,那每次調用都會新建多例bean緩存
二:源碼解析app
org.springframework.beans.factory.support.AbstractBeanFactory#getBean(java.lang.String)ide
@Override public Object getBean(String name) throws BeansException { return doGetBean(name, null, null, false); }
org.springframework.beans.factory.support.AbstractBeanFactory#doGetBeanthis
// Eagerly check singleton cache for manually registered singletons. //bean是單例的話,從緩存讀取 Object sharedInstance = getSingleton(beanName); //若是緩存有,直接返回從緩存中獲取的bean 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); } ........................ //緩存中沒有,獲取該bean的BeanDefinition final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); checkMergedBeanDefinition(mbd, beanName, args);
// Create bean instance. //該BeanDefinition是單例的話 if (mbd.isSingleton()) { sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() { @Override 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); throw ex; } } }); bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd); }
注:單例爲什麼會只建立一次的緣由spa
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#getSingleton(java.lang.String, org.springframework.beans.factory.ObjectFactory<?>)prototype
if (newSingleton) { addSingleton(beanName, singletonObject); }
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#addSingletondebug
/** Cache of singleton objects: bean name --> bean instance */ //單例緩存 private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(256); synchronized (this.singletonObjects) { this.singletonObjects.put(beanName, (singletonObject != null ? singletonObject : NULL_OBJECT)); this.singletonFactories.remove(beanName); this.earlySingletonObjects.remove(beanName); this.registeredSingletons.add(beanName); }
建立單例實例code
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean
// Instantiate the bean. BeanWrapper instanceWrapper = null; if (mbd.isSingleton()) { instanceWrapper = this.factoryBeanInstanceCache.remove(beanName); } if (instanceWrapper == null) { //實例化bean instanceWrapper = createBeanInstance(beanName, mbd, args); } ....................... try { //把依賴bean注入 populateBean(beanName, mbd, instanceWrapper); if (exposedObject != null) { exposedObject = initializeBean(beanName, exposedObject, mbd); } }
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBeanInstance
// 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. //instantiateBean實例化bean return instantiateBean(beanName, mbd);
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#instantiateBean
if (System.getSecurityManager() != null) { beanInstance = AccessController.doPrivileged(new PrivilegedAction<Object>() { @Override public Object run() { //實例化 return getInstantiationStrategy().instantiate(mbd, beanName, parent); } }, getAccessControlContext()); } else { //實例化 beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent); }
org.springframework.beans.factory.support.SimpleInstantiationStrategy#instantiate(org.springframework.beans.factory.support.RootBeanDefinition,java.lang.String,org.springframework.beans.factory.BeanFactory)
RootBeanDefinition bd //用反射,獲取class對象,拿到構造器constructorToUse final Class<?> clazz = bd.getBeanClass(); constructorToUse = clazz.getDeclaredConstructor((Class[]) null);
org.springframework.beans.BeanUtils#instantiateClass(java.lang.reflect.Constructor<T>, java.lang.Object...)
//經過反射,用構造器生成實例 ReflectionUtils.makeAccessible(ctor); return ctor.newInstance(args);
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#populateBean
t-->
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; } ..................... //將PropertyValues pvs放入 BeanWrapper bw中 applyPropertyValues(beanName, mbd, bw, pvs);
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#autowireByName
String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw); for (String propertyName : propertyNames) { if (containsBean(propertyName)) { //遞歸調用,生成依賴鏈對象 Object bean = getBean(propertyName); //將bean的依賴bean放入容器中 pvs.add(propertyName, bean); registerDependentBean(propertyName, beanName); if (logger.isDebugEnabled()) { logger.debug("Added autowiring by name from bean name '" + beanName + "' via property '" + propertyName + "' to bean named '" + propertyName + "'"); } } else { if (logger.isTraceEnabled()) { logger.trace("Not autowiring property '" + propertyName + "' of bean '" + beanName + "' by name: no matching bean found"); } } }
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#applyPropertyValues
if (pvs instanceof MutablePropertyValues) { mpvs = (MutablePropertyValues) pvs; if (mpvs.isConverted()) { // Shortcut: use the pre-converted values as-is. try { //將PropertyValues pvs放入 BeanWrapper bw中 bw.setPropertyValues(mpvs); return; } catch (BeansException ex) { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Error setting property values", ex); } } original = mpvs.getPropertyValueList(); }
//多例 else if (mbd.isPrototype()) { // It's a prototype -> create a new instance. Object prototypeInstance = null; try { beforePrototypeCreation(beanName); //建立多例實例 prototypeInstance = createBean(beanName, mbd, args); } finally { afterPrototypeCreation(beanName); } bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd); }