Core Container模塊:Core 和 Beans 模塊是框架的基礎部分,提供 IoC (控制反轉)和 DI(依賴注入)特性。 Context構建於Core 和 Bean 之上,提供了一個BeanFactory來訪問應用組件,添加了國際化(例如資源綁定)、事件傳播、資源加載等。SpEL提供了強大的表達式語言。 Data Access/Integration模塊:JDBC提供了一個JDBC抽象層,ORM對象關係映射如:JPA,XOM提供了一個ObjectXML映射關係,JMS提供了生產消息和消費消息的功能,Transactions:提供了編程和聲明性的事務管理,這些事務類必須實現特定的接口。 Web模塊:提供了面向Web的特性,好比Spring Mvc,使用servlet listeners初始化IoC容器以及一個面向Web的應用上下文,典型的父子容器關係。 Aop模塊:Aspects模塊提供了對AspectJ集成的支持。Instrumentation模塊提供了class instrumentation支持和classloader實現,動態字節碼插樁。 Test模塊:Test模塊支持使用Junit等對Spring組件進行測試
Ioc的核心思想:資源組件不禁使用方管理,而由不使用資源的第三方管理,這能夠帶來不少好處。第一,資源集中管理,實現資源的可配置和易管理。第二,下降了使用資源雙方的依賴程度,也就是咱們說的耦合度
經常使用的註解:java
@Configuration 相對於配置文件中的<beans> @Bean 相對於配置文件中的<bean> @CompentScan 包掃描 @Scope 配置Bean的做用域 @Lazy 是否開啓懶加載 @Conditional 條件註解 spring boot中常常用到 @Import 導入組件 ......
應用:git
package com.toby.ioc.iocprinciple; import org.springframework.beans.factory.annotation.Autowired; public class PrincipleAspect { @Autowired private PrincipleLog principleLog; /*public PrincipleLog getPrincipleLog() { return principleLog; } public void setPrincipleLog(PrincipleLog principleLog) { this.principleLog = principleLog; }*/ }
package com.toby.ioc.iocprinciple; public class PrincipleBean { }
package com.toby.ioc.iocprinciple; import org.springframework.beans.factory.annotation.Autowire; import org.springframework.context.annotation.*; @Configuration @ComponentScan(basePackages = {"com.toby.ioc.iocprinciple"}) //@ImportResource("classpath:Beans.xml") @Import(PrincipleService.class) public class PrincipleConfig { @Bean public PrincipleBean principleBean(){ return new PrincipleBean(); } //@Bean(autowire = Autowire.BY_TYPE) @Bean public PrincipleAspect principleAspect(){ return new PrincipleAspect(); } @Bean @Primary public PrincipleLog principleLog(){ return new PrincipleLog(); } @Bean public PrincipleLog principleLog2(){ return new PrincipleLog(); } }
package com.toby.ioc.iocprinciple; import org.springframework.stereotype.Controller; @Controller public class PrincipleController { }
package com.toby.ioc.iocprinciple; import org.springframework.stereotype.Repository; @Repository public class PrincipleDao { }
package com.toby.ioc.iocprinciple; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * @desc: 循環依賴 * @author: toby */ @Component public class PrincipleInstanceA { @Autowired private PrincipleInstanceB instanceB; }
package com.toby.ioc.iocprinciple; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * @desc: 循環依賴 * @author: toby */ @Component public class PrincipleInstanceB { @Autowired private PrincipleInstanceA instanceA; }
package com.toby.ioc.iocprinciple; /** * @desc: * @author: toby */ public class PrincipleLog { }
package com.toby.ioc.iocprinciple; /** * @desc: * @author: toby */ public class PrincipleService { }
package com.toby.ioc.iocprinciple; import org.springframework.context.annotation.AnnotationConfigApplicationContext; /** * @desc: ioc原理解析 啓動 * @author: toby */ public class PrincipleMain { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(PrincipleConfig.class); /*for (String beanDefinitionName : context.getBeanDefinitionNames()) { System.out.println("bean定義名稱:" + beanDefinitionName); }*/ PrincipleAspect principleAspect = context.getBean(PrincipleAspect.class); context.close(); System.out.println(principleAspect); } }
完整的代碼請見:springspring
beanfactory的類繼承圖:
編程
首先建立org.springframework.context.annotation.AnnotationConfigApplicationContext#AnnotationConfigApplicationContext(java.lang.Class<?>...)tomcat
public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) { //主要的做用往容器中註冊系統級別的處理器,爲處理咱們自定義的配置類準備,以及初始化classpath下的bean定義掃描 this(); //註冊咱們自定義的配置類 register(annotatedClasses); //Ioc容器刷新12大步 refresh(); }
org.springframework.context.support.AbstractApplicationContext#refresh 12大步springboot
public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { //1:準備刷新上下文環境 prepareRefresh(); //2:獲取初始化Bean工廠 ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); //3:對bean工廠進行填充屬性 prepareBeanFactory(beanFactory); try { //4:Spring開放接口 留給子類去實現該接口 postProcessBeanFactory(beanFactory); //:5:調用咱們的bean工廠的後置處理器 invokeBeanFactoryPostProcessors(beanFactory); // 6:註冊咱們bean後置處理器 registerBeanPostProcessors(beanFactory); // 7:初始化國際化資源處理器 initMessageSource(); //8:初始化事件多播器 initApplicationEventMulticaster(); //9:// 這個方法一樣也是留個子類實現的springboot也是從這個方法進行啓動tomcat的. onRefresh(); //10:把咱們的事件監聽器註冊到多播器上 registerListeners(); //11:實例化全部的非懶加載的單實例bean finishBeanFactoryInitialization(beanFactory); //12:最後刷新容器 發佈刷新事件(Spring cloud eureka也是從這裏啓動的) finishRefresh(); } catch (BeansException ex) { if (logger.isWarnEnabled()) { logger.warn("Exception encountered during context initialization - " + "cancelling refresh attempt: " + ex); } // Destroy already created singletons to avoid dangling resources. destroyBeans(); // Reset 'active' flag. cancelRefresh(ex); // Propagate exception to caller. throw ex; } finally { // Reset common introspection caches in Spring's core, since we // might not ever need metadata for singleton beans anymore... resetCommonCaches(); } } }
第11步:實例化全部的非懶加載的單實例bean
org.springframework.context.support.AbstractApplicationContext#finishBeanFactoryInitializationapp
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) { // Initialize conversion service for this context. 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)); } // Register a default embedded value resolver if no bean post-processor // (such as a PropertyPlaceholderConfigurer bean) registered any before: // at this point, primarily for resolution in annotation attribute values. if (!beanFactory.hasEmbeddedValueResolver()) { beanFactory.addEmbeddedValueResolver(new StringValueResolver() { @Override public String resolveStringValue(String strVal) { return getEnvironment().resolvePlaceholders(strVal); } }); } // 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); //凍結全部的bean定義 beanFactory.freezeConfiguration(); //實例化剩餘的非懶加載的單實例bean beanFactory.preInstantiateSingletons(); }
實例化剩餘的非懶加載的單實例bean:框架
@Override public void preInstantiateSingletons() throws BeansException { if (logger.isDebugEnabled()) { logger.debug("Pre-instantiating singletons in " + this); } // 獲取容器中全部beanName List<String> beanNames = new ArrayList<String>(this.beanDefinitionNames); //觸發實例化全部的非懶加載的單實例bean for (String beanName : beanNames) { //合併bean定義 RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName); //非抽象,單實例,非懶加載 if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) { //是否工廠bean,是要獲取factorybean的getObject方法 if (isFactoryBean(beanName)) { //factorybean的bean那麼前面加了一個FACTORY_BEAN_PREFIX就是& final FactoryBean<?> factory = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName); boolean isEagerInit; if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) { isEagerInit = AccessController.doPrivileged(new PrivilegedAction<Boolean>() { @Override public Boolean run() { return ((SmartFactoryBean<?>) factory).isEagerInit(); } }, getAccessControlContext()); } else { isEagerInit = (factory instanceof SmartFactoryBean && ((SmartFactoryBean<?>) factory).isEagerInit()); } if (isEagerInit) { //調用getBean流程 getBean(beanName); } } else {//非工廠bean //調用getBean流程 getBean(beanName); } } } //觸發初始化以後的回調,到這裏全部的bean都存放在了單例緩衝池中了 for (String beanName : beanNames) { Object singletonInstance = getSingleton(beanName); if (singletonInstance instanceof SmartInitializingSingleton) { final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance; if (System.getSecurityManager() != null) { AccessController.doPrivileged(new PrivilegedAction<Object>() { @Override public Object run() { smartSingleton.afterSingletonsInstantiated(); return null; } }, getAccessControlContext()); } else { //觸發實例化以後的方法afterSingletonsInstantiated smartSingleton.afterSingletonsInstantiated(); } } } }
getBean流程
org.springframework.beans.factory.support.AbstractBeanFactory#getBean(java.lang.String)ide
public Object getBean(String name) throws BeansException { //獲取bean return doGetBean(name, null, null, false); }
org.springframework.beans.factory.support.AbstractBeanFactory#doGetBean函數
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; // Eagerly check singleton cache for manually registered singletons. //先從單例緩衝池中獲取,第一次確定沒有,後面都有 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 + "'"); } } //爲何不直接返回,緣由就是多是FactoryBean 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); } // Check if bean definition exists in this factory. //獲取父容器 BeanFactory parentBeanFactory = getParentBeanFactory(); 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 { //合併bean定義 final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); //檢查當前建立的bean定義是否是抽象 checkMergedBeanDefinition(mbd, beanName, args); //處理依賴bean,獲取依賴bean名稱 String[] dependsOn = mbd.getDependsOn(); if (dependsOn != null) { for (String dep : dependsOn) { if (isDependent(beanName, dep)) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'"); } //保存的是依賴和beanName之間的映射關係 registerDependentBean(dep, beanName); try { //獲取依賴的bean getBean(dep); } catch (NoSuchBeanDefinitionException ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "'" + beanName + "' depends on missing bean '" + dep + "'", ex); } } } //建立單例bean if (mbd.isSingleton()) { //把beanName 和一個singletonFactory匿名內部類傳入用於回調 sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() { @Override 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 = getObjectForBeanInstance(sharedInstance, name, beanName, mbd); } 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); } else { String scopeName = mbd.getScope(); final Scope scope = this.scopes.get(scopeName); if (scope == null) { throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'"); } try { Object scopedInstance = scope.get(beanName, new ObjectFactory<Object>() { @Override 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.isInstance(bean)) { 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; }
createBean:
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBean(java.lang.String, org.springframework.beans.factory.support.RootBeanDefinition, java.lang.Object[])
protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException { if (logger.isDebugEnabled()) { logger.debug("Creating instance of bean '" + beanName + "'"); } RootBeanDefinition mbdToUse = mbd; // Make sure bean class is actually resolved at this point, and // clone the bean definition in case of a dynamically resolved Class // which cannot be stored in the shared merged bean definition. Class<?> resolvedClass = resolveBeanClass(mbd, beanName); if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) { mbdToUse = new RootBeanDefinition(mbd); mbdToUse.setBeanClass(resolvedClass); } // Prepare method overrides. try { mbdToUse.prepareMethodOverrides(); } catch (BeanDefinitionValidationException ex) { throw new BeanDefinitionStoreException(mbdToUse.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, mbdToUse); if (bean != null) { return bean; } } catch (Throwable ex) { throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName, "BeanPostProcessor before instantiation of bean failed", ex); } //幹活的do方法,真正的建立咱們的bean的實例對象的過程 Object beanInstance = doCreateBean(beanName, mbdToUse, args); if (logger.isDebugEnabled()) { logger.debug("Finished creating instance of bean '" + beanName + "'"); } return beanInstance; }
doCreateBean
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) throws BeanCreationException { //實例化BeanWrapper是對Bean的包裝 BeanWrapper instanceWrapper = null; if (mbd.isSingleton()) { 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); mbd.resolvedTargetType = beanType; // Allow post-processors to modify the merged bean definition. synchronized (mbd.postProcessingLock) { if (!mbd.postProcessed) { try { //調用後置處理 applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName); } catch (Throwable ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Post-processing of merged bean definition failed", ex); } 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"); } //把咱們的早期對象包裝成一個singletonFactory對象 該對象提供了一個getObject方法 addSingletonFactory(beanName, new ObjectFactory<Object>() { @Override public Object getObject() throws BeansException { return getEarlyBeanReference(beanName, mbd, bean); } }); } // Initialize the bean instance. Object exposedObject = bean; try { //給咱們的屬性進行賦值(調用set方法進行賦值) populateBean(beanName, mbd, instanceWrapper); if (exposedObject != null) { //初始化,動態代理也在這裏生成 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) { 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; }
initializeBean
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#initializeBean(java.lang.String, java.lang.Object, org.springframework.beans.factory.support.RootBeanDefinition)
protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) { if (System.getSecurityManager() != null) { AccessController.doPrivileged(new PrivilegedAction<Object>() { @Override public Object run() { invokeAwareMethods(beanName, bean); return null; } }, getAccessControlContext()); } else { //咱們的bean實現了XXXAware接口進行方法的回調 invokeAwareMethods(beanName, bean); } Object wrappedBean = bean; if (mbd == null || !mbd.isSynthetic()) { //調用咱們的bean的後置處理器的postProcessorsBeforeInitialization方法 注意@PostConstruct在這步處理調用 wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName); } try { //調用初始化方法,好比實現了InitializingBean接口,回調InitializingBean的afterPropertiesSet()方法或者調用自定義的init方法 invokeInitMethods(beanName, wrappedBean, mbd); } catch (Throwable ex) { throw new BeanCreationException( (mbd != null ? mbd.getResourceDescription() : null), beanName, "Invocation of init method failed", ex); } if (mbd == null || !mbd.isSynthetic()) { //調用咱們bean的後置處理器的PostProcessorsAfterInitialization方法 wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName); } return wrappedBean; }
getBean的流程圖以下