博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
用伪代码梳理spring源码
阅读量:5088 次
发布时间:2019-06-13

本文共 73960 字,大约阅读时间需要 246 分钟。

1、第一个spring demo

BeanFactory bf = new XmlBeanFactory(new ClassPathResource("beanFactoryTest.xml"));// 1. new ClassPathResource("beanFactoryTest.xml")    |-- 配置文件封装         |-- interface InputStreamSource              |-- InputStream getInputStream();        |-- interface Resource extends InputStreamSource             |-- boolean exists(); // 存在性            |-- boolean isReadable(); // 可读性            |-- boolean isOpen(); // 是否处于打开状态            |-- URL getURL(); //             |-- URI getURI();            |-- File getFile();            |-- long lastModified();            |-- Resource createRelative(String relitivePath);            |-- String getFileName();            |-- String getDescription();        |-- ClassPathResource implements Resource {                @Override                InputStream getInputStream() {                    if (this.clazz != null){                        is = this.clazz.getResourceAsStream(this.path);                    } else {                        is = this.classLoader.getResourceAsStream(this.path);                    }                }            }        |-- FileSystemResource implements Resource {                @Override                InputStream getInputStream() {                    return new FileInputStream(this.file);                }            }        ...

2、XmlBeanFactory跟踪

// 2. new XmlBeanFactory(Resource resource)        |-- 2.1 XmlBeanFactory(Resource resource) throws BeansException {this(resource, null);}|-- 2.1 XmlBeanFactory(Resource resource, BeanFactory parentFactory) throws BeansException {super(parentFactory); // parentFactory为父类BeanFactory,用于factory合并,可以为空this.reader.loadBeanDefinitions(resource); // XmlBeanDefinitionReader reader;}|-- 2.1.1 super(parentFactory) |-- class AbstractAutowrieCapableBeanFactory|-- public AbstractAutowrieCapableBeanFactory(){super();// 忽略给定接口的自动装配ignoreDependencyInterface(BeanNameAware.class); ignoreDependencyInterface(BeanFactoryAware.class);ignoreDependencyInterface(BeanClassLoaderAware.class);}|-- 2.1.2 this.reader.loadBeanDefinitions(resource)|-- class XmlBeanDefinitionReader|-- int loadBeanDefinitions(Resource resource){return loadBeanDefinitions(new EncodedResource(resource));}|-- EncodedResource(Resource resource){this.resource = resource;}Reader getReader(){if (this.encoding != null){return new InputStreamReader(this.resource.getInputStream(), this.encoding);} else {return new InputStreamReader(this.resource.getInputStream());}}|-- int loadBeanDefinitions(EncodedResource encodedResource) {...// 通过属性来记录已经加载的资源 this.resourceCurrentBeingLoaded -> new ThreadLocal
>;Set
currentResources = this.resourceCurrentBeingLoaded.get();if (currentResource == null) {currentResources = new HashSet
(4);this.resourceCurrentBeingLoaded.set(currentResources);}// if (!currentResource.add(currentResource)){throw e;}try {InputStream inputStream = encodedResource.getResource().getInputStream();org.xml.sax.InputSource inputSource = new org.xml.sax.InputSource();// 设置编码if (encodedResource.getEncoding() != null) {inputSource.setEncoding(encodedResource.getEncoding());}// 真正进入业务逻辑处理return doLoadBeanDefinitions(inputSource, encodedResource.getResource());} catch(e){...} finally {...}}|-- doLoadBeanDefinitions(inputSource, encodedResource.getResource())|-- int doLoadBeanDefinitions(InputSource inputSource, Resource resource){try {// 获取xml文件验证模式int validationModel = getValidationModeForResource(resource);// 加载xml文件得到对应的DocumentDocument doc = this.documentLoader.loadDocument( inputSource, getEntityResolver(), this.errorHandler, validationModel, isNamespaceAware());// 根据返回的Document对象注册Bean信息return registerBeanDefinitions(doc, resource);} catch (e){...}}|-- 2.1.2.1 获取xml文件验证模式|-- DTD
...
... ...|-- XSD
... ...
...
|-- getValidationModeForResource(resource)|-- int getValidationModeForResource(Resource resource) { int validationModeToUse = getValidationMode(); // 如果手动指定了验证模式则使用指定的验证模式 if (validationModeToUse != VALIDATION_AUTO) { return validationModeToUse; } // 如果未指定则使用自动检测 int detectedMode = dectectValidationMode(resource); if (detectedMode != null) { return detectedMode; } return VALIDATION_XSD;}|-- int dectectValidationMode (Resource resource) { if (resource.isOpen()) { throw e; } InputStream inputStream; try { inputStream = resource.getInputStream(); } catch(e){ throw e; } try { return this.validationModeDelector.detectValidationMode(inputStream); } catch(e){ throw e; }}|-- int XmlValidationModeDetector.detectValidationMode(InputStream inputStream) { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); try { boolean isDtdValidated = false; String content; while ((content = reader.readLine())!= null){ content = consumeCommentTokens(content); // 空行或者注释略过 if (this.inComment || !StringUtils.hasText(content)){ continue } if (hasDoctype(content)) { isDtdValidated = true; break; } // 读取到
<跳出 if (hasopeningtag(content)) { break; } return (isdtdvalidated ? validation_dtd : validation_xsd); catch (e){ throw e; finally reader.close(); }}boolean hasdoctype(string content){ (content.indexof(doctype)>
-1);}|-- 2.1.2.2 获取Document |-- this.documentLoader.loadDocument(inputSource, getEntityResolver(), this.errorHandler, validationModel, isNamespaceAware())|-- DefaultDocumentLoader.loadDocument(InputSource inputSource, EntityResolver entityResolver, ErrorHandler errorHandler, int validationModel, boolean namespaceAware) { DocumentBuilderFactory factory = createDocumentBuilderFactory(validationModel, namespaceAware); DocumentBuilder builder = createDocumentBuilder(factory, entityResolver, errorHandler); return builder.parse(inputSource);}|-- EntityResolver // 外部实体|-- InputSource resolveEntity(String publicId, String systemId)
... ...
--> publicId: null, systemId: http://www.Springframework.org/schema/beans/Spring-beans.xsd
... ...
--> publicId: -//Spring//DTD BEAN 2.0//EN, systemId: http://www.Springframework.org/dtd/Spring-beans-2.0.dtd|-- getEntityResolver() -> DelegatingEntityResolver|-- InputSource resolveEntity(String publicId, String systemId) throws e{ if (systemId != null) { if (systemId.endsWith(DTD_SUFFIX)){ // 如果是dtd return this.dtdResolver.resolveEntity(publicId, systemId); } else if(systemId.endsWith(XSD_SUFFIX)) { // 通过调用META-INF/Spring.schemas解析 return this.schemaResolver.resolveEntity(publicId, systemId); } } return null; }|-- BeansDtdResolver |-- InputSource resolveEntity(String publicId, String systemId) { // DTD_EXTENSION=".dtd" if (systemId != null && systemId.endsWith(DTD_EXTENSION)){ int lastPathSeparator = systemId.lastIndexOf("/"); for (String DTD_NAME : DTD_NAMES) { // DTD_NAMES={"Spring-beans-2.0","Spring-beans"} int dtdNameStart = systemId.indexOf(DTD_NAME); if (dtdNameStart > lastPathSeparator) { String dtdFile = systemId.substring(lastPathSeparator); try { Resource resource = new ClassPathReource(dtdFile, getClass()); InputSource source = new InputSource(resource.getInputStream()); source.setPulicId(publicId); source.setSystemId(systemId); return source; } catch (e) { throw e; } } } } return null; }|-- 2.1.2.3 解析及注册BeanDefinitions|-- registerBeanDefinitions(doc, resource)|-- XmlBeanDefinitionReader { public int registerBeanDefinitions(Document doc, Resource resource) { // 使用默认的DefaultBeanDefinitionDocumentReader实例化BeanDefinitionDocumentReader BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader(); // 将环境变量设置其中 documentReader.setEnvironment(this.getEnvironment()); // 在实例化BeanDefinitionDocumentReader时会将BeanDefinionRegistry传入,默认使用继承自DefaultListableBeanFactory的子类 // 记录统计前BeanDefiniton的加载个数 int countBefore = getRegistry().getBeanDefinitionCount(); // 加载及注册bean documentReader.registerBeanDefinitions(doc, createReaderContext(resource)); // 记录本次加载的BeanDefinition个数 return getRegistry().getBeanDefinitionCount() - countBefore; } public int registerBeanDefinitions(Document doc, XmlReaderContext readerContext) { this.readerContext = readerContext; Element root = doc.getElement(); doRegisterBeanDefinitions(root); } // 核心方法 protected void doRegisterBeanDefinitions(Element root){ // 处理profile /** *
*
...
*
...
*
...
*
*
*
Spring.profiles.active
*
dev|test|prod
* */ String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE); if (StringUtils.hasText(profileSpec)) { String[] specfiedProfiles = StringUtils.tokenizedToStringArray(profileSpec, ","); if (!this.environment.acceptsProfiles(specfiedProfiles)) { return; } } // 专门处理解析 BeanDefinitionParserDelegate parent = this.delegate; this.delegate = createHelper(readerContext, root, parent); // begin preProcessXml(root); // 钩子方法 parseBeanDefinitions(root, this.delegate); postProcessXml(root); // 钩子方法 // end this.delegate = parent; } // 专门处理解析 /** * 默认标签:
* 自定义标签:
*/ protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) { // 对beans的处理 if (delegate.isDefaultNamespace(root)) { NodeList nl = root.getChildNodes(); for (int i = 0; i < nl.length(); i++) { Node node = nl.item(i); if (node instanceof Element) { Element ele = (Element) node; // 对bean的处理 parseDefaultElement(ele, delegate); } else { // 对bean的处理 delegate.parseCustomElement(ele); } } } else { // 对bean的处理 delegate.parseCustomElement(ele); } }}

3、默认标签的解析

|-- 3 默认标签的解析|-- private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {// 对import标签处理if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)){    importBeanDefinitionResource(ele);}// 对alias标签处理else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)){    processAliasRegistration(ele);}// 对bean标签处理else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)){    processBeanDefinition(ele, delegate);}// 对beans标签处理else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)){    doRegisterBeanDefinitions(ele);}}|-- 3.1.1 对beans标签处理|-- protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {    // 委托BeanDefinitionParserDelegate类解析,bdHolder实例包含class、name、id、alias之类的属性    BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);    if (bdHolder != null) {        // bdHolder不为空情况下,若存在默认标签的子节点下再有自定义属性,还需要再次注册        bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);        try {            // 注册操作委托BeanDefinitionReaderUtils.registerBeanDefinition方法            BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());        } catch (e) {            throw e;        }        // 发出响应事件,通知想关的监听器,这个bean已经加载完成了        getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));    }}|-- BeanDefinitionParserDelegate.parseBeanDefinitionElement(Element ele) {    return parseBeanDefinitionElement(ele, null);}parseBeanDefinitionElement(Element ele, BeanDefinition containingBean) {    // 解析id属性    String id = ele.getAttribute(ID_ATTRIBUTE);    // 解析name属性    String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);    // 分割name属性    List
aliases = new ArrayList
(); if (StringUtils.hasLength(aliases)) { String[] nameArr = StringUtils.tokenizedToStringArray(nameAttr, ","); aliases.addAll(nameArr); } String beanName = id; if (!StringUtils.hasText(beanName) && !aliases.isEmpty()) { beanName = aliases.remove(0); //?? } if (containingBean == null) { checkNameUniqueness(beanName, aliases, ele); } // 进一步解析其他所有属性并统一封装至GenericBeanDefinition AbstractBeanparseBeanDefinition beanDefinition = parseBeanDefinitionElement(ele, beanName, containingBean); if (beanDefinition != null) { if (!StringUtils.hasText(beanName)) { // 未指定beanName,使用默认规则为此bean生成beanName if (containingBean != null) { // 不存在name beanName = BeanDefinitionReaderUtils.generateBeanName(beanDefinition, this.readerContext.getRegistry(), true); } else { beanName = this.readerContext.generateBeanName(beanDefinition); String beanClassName = beanDefinition.getBeanClassName(); if (beanClassName != null && beanName.startsWith(beanClassName) && beanName.length() > beanClassName.length() && !this.readerContext.getRegistry().IsBeanNameInUse(beanClassName)) { aliases.add(beanClassName); } } } // 将获取到的信息封装到BeanDefinitionHolder中 String[] aliasesArray = StringUtils.toStringArray(aliases); return new BeanDefinitionHolder(beanDefinition, beanName, aliasesArray); } return null;}// 进一步解析其他所有属性并统一封装至GenericBeanDefinitionAbstractBeanparseBeanDefinition parseBeanDefinitionElement(Element ele, String beanName, BeanDefinition containingBean) { try { this.parseState.push(new BeanEntry(beanName)); String className = null; // 解析class属性 if (ele.hasAttribute(CLASS_ATTRIBUTE)) { className = ele.getAttribute(CLASS_ATTRIBUTE).trim(); } // 解析parent属性 String parent = null; if (ele.hasAttribute(PARENT_ATTRIBUTE)) { parent = ele.getAttribute(PARENT_ATTRIBUTE).trim(); } // 创建用于属性承载的BeanDefinition AbstractBeanDefinition bd = createBeanDefinition(className, parent); // 硬编码解析默认的bean属性 parseBeanDefinitionAttributes(ele, beanName, containingBean, bd); // 提取description bd.setDescription(DomUtils.getChildElementValueByTagName(ele, DESCRIPTION_ELEMENT)); // 解析元数据 parseMetaElements(ele, bd); // 解析lookup-method parseLookupOverriedSubElements(ele, bd.getMethodOverries()); // 解析replacted-method属性 parseReplactedMethodSubElements(ele, bd.getMethodOverries()); // 解析构造函数参数 parseConstructorArgElements(ele, bd); // 解析property子元素 parsePropertyElements(ele, bd); // 解析qualifier子元素 parseQualifierElements(ele, bd); bd.setResource(this.readerContext.getResource()); bd.setSource(extractSource(ele)); return bd; } catch (e) { throw e; } finally { this.parseState.pop(); } return null;}// 创建用于属性承载的BeanDefinitionprotected AbstractBeanDefinition createBeanDefinition(String className, String parentName){ return BeanDefinitionReaderUtils.createBeanDefinition(parentName, className, this.readerContext.getBeanClassLoader());}// BeanDefinitionReaderUtils-> createBeanDefinitionpublic static AbstractBeanDefinition createBeanDefinition(String parentName, String className, ClassLoader classloader) { GenericBeanDefinition bd = new GenericBeanDefinition(); // parentName可能为空 bd.setParentName(parentName); if (className != null) { if (classLoader != null) { bd.setBeanClass(ClassUtil.forName(className, classLoader)); } else { bd.setBeanClassName(className); } } return bd;}// 硬编码解析默认的bean属性public AbstractBeanDefinition parseBeanDefinitionAttributes(Element ele, String beanName, BeanDefinition containingBean, AbstractBeanDefinition bd) { // 解析scope属性 // 解析singleton属性 bd.setScope(ele.getAttribute(SCOPE_ATTRIBUTE) || ele.getAttribute(SINGLETON_ATTRIBUTE) || containingBean.getScope()); // 解析abstract属性 bd.setAbstract(ele.getAttribute(ABSTRACT_ATTRIBUTE)); // 解析lazy-init属性 bd.setLazyInit(lazy-init); // 解析autowire属性 // 解析dependency-check属性 // 解析dependency-on属性 // 解析autowire-candidate属性 // 解析primary属性 // 解析init-method属性 // 解析detory-method属性 // 解析factory-method属性 // 解析factory-bean属性 ...}// 解析Meta元素
parseMetaElements(Element ele, BeanMetadataAttributeAccessor attributeAccessor) { // 获取当前节点的所有子元素 ...}

4、bean的加载

MyTestBean bean = (MyTestBean) bf.getBean("myTestBean");

步骤:
(1) 转换对应的beanName
 name="&aa"=>name="aa" || A->B->C=>C
(2) 尝试从缓存中加载单例
 singletonFactories集合缓存ObjectFactory
(3) bean的实例化
 getObjectForBeanInstance(sharedInstance, name, beanName, mbd)
(4) 原型模式的依赖检查
 A有B属性,B有A属性,属性循环依赖
 isPrototypeCurrentlyInCreation(beanName)
(5) 检测parentBeanFactory
(6) 将存储XML配置文件的GernericBeanDefinition转换为RootBeanDefinition
(7) 寻找依赖
(8) 针对不同的scope进行bean的创建
 scope="singleton||prototype||other"
(9) 类型转换
 return (T) bean;
代码实现如下:

(1) 转换对应的beanNameString beanName = transformedBeanName(name);(2) 尝试从缓存中加载单例T doGetBean(args ...){    Object bean;     sharedInstance = getSingleton(beanName);    (3) bean的实例化    if (!sharedInstance) { // 非单例        bean = getObjectForBeanInstance(beanName, mbd, args);    } else { // 单例        (4) 原型模式的依赖检查        if (isPrototypeCurrentlyInCreation(beanName)) throw e;                (5) 检测parentBeanFactory        BeanFactory parentBeanFactory = getParentBeanFactory();        if (parentBeanFactory != null) {            nameToLoopup = orginalBeanName(name);            // 递归到BeanFactory中寻找            return parentBeanFactory.getBean(nameToLoopup, args);        }                (6) 将存储XML配置文件的GernericBeanDefinition转换为RootBeanDefinition        final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);        checkMergedBeanDefinition(mbd, beanName, args);                (7) 寻找依赖        // 存在依赖,递归实例化bean        String[] dependsOn = mbd.getDependsOn();        if (dependsOn != null) {            for (String dependsOnBean : dependsOn){                getBean(dependsOnBean);                registerDependentBean(dependsOnBean);            }        }                (8) 针对不同的scope进行bean的创建        // 实例化mbd本身        if (mbd.isSingleton()){            sharedInstance = getSingleton(beanName, new ObjectFactory(){                    getObject() {                        try {                            return createBean(beanName, mbd, args);                        } catch(e) {                            destoryName(beanName);                            throw e;                        }                    }                });            bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);        } else if (mbd.isPrototype()) {            prototypeInstance;            try {                beforePrototypeCreation(beanName);                prototypeInstance = createBean(beanName, mbd, args);            } finally {                afterPrototypeCreation(beanName);            }            bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);        } else {            // 指定的scope上实例化bean            String scopeName = mbd.getScope();            final Scope scope = this.scopes.get(scopeName);            scopeInstance = scope.get(beanName, new ObjectFactory() {                getObject() {                    try {                        return createBean(beanName, mbd, args);                    } finally {                        afterPrototypeCreation(beanName);                    }                }            });            bean = getObjectForBeanInstance(scopeInstance, name, beanName, mbd);        }    }    (9) 类型转换    if (requriedType != null) {        return getTypeConverter().convertIfNecessary(bean, requiredType);    }    return (T) bean;}

5.1 FactoryBean接口类

FactoryBean    |-- T getObject(); //     |-- Class
getObjectType(); |-- boolean isSingleton();CarFactoryBean implements FactoryBean
{ Car getObject() { Car car = new Car(); String[] infos = carInfo.split(","); car.setBrand(infos[0]); car.setMaxSpeed(Integer.valueOf(infos[1])); car.setPrice(Double.valueOf(infos[2])); return car; } String carInfo; // setter、getter方法 isSingleton() { return false; }}
代码实现: getBean("car") -> spring发现CarFactoryBean implements FactoryBean接口,容器调用接口方法CarFactoryBean#getObject()返回 getBean("&car") -> CarFactoryBean

 

5.2 缓存中获取单例

Object getSingleton(String beanName) {    return getSingleton(beanName, true);}Object getSingleton(beanName, allowEarlyReference) {    // 检查缓存是否存在    Object singletonObject = this.singletonObjects.get(beanName);    if (null == getSingleton) {        synchronized(this.singletonObjects) {            singletonObject = this.earlySingletonObjects.get(beanName);            if (singletonObject == null && allowEarlyReference) {                // 当某些方法需要提前初始化的时候会调用addSingletonFactory方法将对应的ObjectFactory初始化策略存储在singletongFactories                ObjectFactory singletonFactory = this.singletonFactories.get(beanName);                if (singletonFactory != null) {                    // 调用预先设定的getObject方法                    singletonObject = singletonFactory.getObject();                    // 记录在缓存中,earlySingletonObjects与singletonFactories互斥                    this.earlySingletonObjects.put(beanName, singletonObject);                    this.singletonFactories.remove(beanName);                }            }        }    }    return singletonObject != NULL_OBJECT ? singletonObject : null;}

5.3 从bean的实例中获取对象

(1) 对FactoryBean做正确性的验证(2) 对非FactoryBean不做任务处理(3) 对bean进行转换(4) 将从Factory中解析bean的工作委托给getObjectFromFactoryBeangetObjectForBeanInstance(beanInstance, name, beanName, mbd) {    // &testBeanFactory    if (BeanFactoryUtils.isFactoryDereference(name) && !(beanInstance instanceof FactoryBean)) {        throw e;    }    // &testBeanFactory    if (!(beanInstance instanceof FactoryBean) || BeanFactoryUtils.isFactoryDereference(name)) {        return beanInstance;    }    // 加载factoryBean    Object object = null;    if (mbd == null) {        // 尝试从缓存中加载bean        object = getCachedObjectForFactoryBean(beanName);    }    if (object == null) {        FactoryBean
factory = (FactoryBean
) beanInstance; if (mbd == null && containsBeanDefinition(beanName)) { mbd = getMergedLocalBeanDefinition(beanName); } // 是否是用户定义的而不是应用程序本身定义的 boolean synthetic = (mbd != null && mbd.isSynthetic()); object = getObjectFromFactoryBean(factory, beanName, !synthetic); }}getObjectFromFactoryBean(factory, beanName, shouldPostProcess) { // 如果是单例 if (factory.isSingleton() && containsSingleton(beanName)) { synchronized(getSingletonMutex()) { Object object = this.factoryBeanObjectCache.get(beanName); if (object == null) { object = doGetObjectFromFactoryBean(factory, beanName, shouldPostProcess); this.factoryBeanObjectCache.put(beanName, object); } return object; } } else { return doGetObjectFromFactoryBean(factory, beanName, shouldPostProcess); }}doGetObjectFromFactoryBean(factory, beanName, shouldPostProcess) { Object object = null; try { if (System.getSecurityManager() != null) { // 权限验证 try { Object = AccessController.doPrivileged(new PrivilegedExceptionAction(){ run() { return factory.getObject(); } }); } catch (e) { throw e; } } else { object = factory.getObject(); } } catch (e) { throw e; } if (object != null && shouldPostProcess) { try { object = postProcessObjectFromFactoryBean(object, beanName); } catch (e) { throw e; } } return object;}postProcessObjectFromFactoryBean(object, beanName) { return applyBeanPostProcessorsAfterInitialization(object, beanName);}applyBeanPostProcessorsAfterInitialization(existingBean, beanName) { Object result = existingBean; for (BeanPostProcessor beanPostProcessor : getBeanPostProcessors()) { result = beanPostProcessor.postProcessorsAfterInitialization(result, beanName); return result; } return result;}

5.4 获取单例

(1) 检查缓存是否已经加载过(2) 若没有加载,则记录beanName的正在加载状态(3) 加载单例前记录加载状态(4) 通过调用参数传入的ObjectFactory的个体Object实例化bean(5) 加载单例后的处理方法调用(6) 将结果记录到缴存并删除加载bean过程中所记录的各种辅助状态(7) 返回处理结果getSingleton(beanName, new ObjectFactory) {    synchronized (this.singletonObjects) {        Object singletonObject = this.singletonObjects.get(beanName);        if (singletonObject == null) {            beforeSingletonCreation(beanName);            try {                singletonObject = singletonFactory.getObject();            } catch (e) {                throw e;            } finally {                afterSingletonCreation(beanName);            }            // 加入缓存            addSingleton(beanName, singletonObject);        }    }    return (singletonObject != NULL_OBJECT ? singletonObject : null)}beforeSingletonCreation(beanName) {    if (!this.singletonsCurrentlyCreation.add(beanName)) { // 将当前正要创建的bean记录在缓存中,这样便可以对循环依赖进行检测        throw e;    }}afterSingletonCreation(beanName) {    if (!this.singletonsCurrentlyCreation.remove(beanName)) { // 加载结束后,移除缓存中对该bean正在加载状态的记录        throw e;    }}addSingleton(beanName, singletonObject) {    synchronized (this.singletonObjects) {        // 将结果记录到缓存,并删除加载bean过程中所记录的辅助状态        this.singletonObjects.put(beanName, singletonObject);        this.singletonFatories.remove(beanName);        this.earlySingletonObjects.remove(beanName);        this.registeredSingletons.add(beanName);    }}getSingleton(beanName, new ObjectFactory(){    public Object getObject() {        try {            return createBean(beanName, mbd, args);        } catch (e) {            throw e;        }    }});

5.5 准备创建bean

(1) 根据设置的class属性,或者根据className来解析class(2) 对override属性进行标记及验证(3) 应用初始化前的后处理器,解析指定bean是否存在初始化前的短路操作(4) 创建beancreateBean(beanName, mbd, args) {    // 根据设置的class属性,或者根据className来解析class    resolveBeanClass(mbd, beanName);        // 对override属性进行标记及验证    try {        mbd.prepareMethodOverrides();    } catch (e) {        throw e;    }    // 给BeanPostProcessors一个机会返回代理来替代真正的实例    Object bean = resolveBeforeInstantiation(beanName, mbd);    if (bean != null) {        return bean;    }    // 创建bean    Object beanInstance = doCreateBean(beanName, mbd, args);    return beanInstance;}prepareMethodOverrides() {    MethodOverrides methodOverrides = getMethodOverrides();    for (MethodOverride mo : MethodOverrides) {        prepareMethodOverride(mo);    }}// lookup-method、replace-method属性prepareMethodOverride(mo) {    // 获取对应类中对应方法名的个数    int count = ClassUtils.getMethodCountForName(getBeanClass(), mo.getMethodName());    if (count == 0) {        throw e;    } else if (count == 1) {        // 标记未被覆盖,避免参数类型检查的开销        mo.setOverloaded(false);    }}|-- 实例化前置处理resolveBeforeInstantiation(beanName, mbd) {    Object bean = null;    try {        bean = applyBeanPostProcessorsBeforeInitialization(mbd.getBeanClass(), beanName);        if (bean != null) {            bean = applyBeanPostProcessorsAfterInitialization(mbd.getBeanClass(), beanName);        }        mbd.beforeInstantiationResolved = (bean != null);    } catch (e) {        throw e;    }    return bean;}|-- 实例化前的处理器应用applyBeanPostProcessorsBeforeInitialization(beanClass, beanName) {    for (BeanPostProcessor bp : getBeanPostProcessors()) {        if (bp instanceof InstantiationAwareBeanPostProcessor) {            InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor)bp;            Object result = ibp.postProcessorsBeforeInitialization(beanClass, beanName);            if (result != null) {                return result;            }        }    }    return null;}|-- 实例化后的处理器应用applyBeanPostProcessorsAfterInitialization(existingBean, beanName) {        Object result = existingBean;    for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {        Object result = beanProcessor.postProcessorsAfterInitialization(result, beanName);        if (result != null) {            return result;        }    }    return result;}

5.6 循环依赖

(1) 循环依赖定义:    循环依赖就是循环引用,就是存在2个或多个bean相互之间的持有对方,如:A->B->C->A,A->B->A(2) 循环依赖的类型:    构造器循环依赖、setter循环依赖5.6.1 构造器循环依赖处理    TestA、TestB、TestC    TestA -> 查找“当前创建bean池”,如果没发现则继续准备构造器参数“testB”,并将“testA”标识符放到“当前创建bean池”    TestB -> 查找“当前创建bean池”,如果没发现则继续准备构造器参数“testC”,并将“testB”标识符放到“当前创建bean池”    TestC -> 查找“当前创建bean池”,如果没发现则继续准备构造器参数“testA”,并将“testC”标识符放到“当前创建bean池”    准备构造器参数“testA”时,发现该 bean的标识符在“当前创建bean池”存在,抛出BeanCurrentlyInCreationException。    5.6.2 setter循环依赖处理    TestA、TestB、TestC    TestA -> 暴露ObjectFactory工厂,并将“testA”标识符放到“当前创建bean池”,然后进行setter注入“testB”    TestB -> 暴露ObjectFactory工厂,并将“testB”标识符放到“当前创建bean池”,然后进行setter注入“testC”    TestC -> 暴露ObjectFactory工厂,并将“testC”标识符放到“当前创建bean池”,然后进行setter注入“testA”,进入注入“TestA”时由于提前暴露了“ObjectFactory”工厂,从而使用它返回提前暴露一个创建中的bean。    最后依赖注入"TestB"、"TestA",完成setter注入。    5.6.3 prototype范围的依赖处理    scope="prototpye" -> 由于prototpye作用域无法完成依赖注入,spring容器不进行缓存prototype作用域的bean,因此无法提前暴露一个创建中的bean。    scope="singleton" -> setAllowCircularReferences(false); // 禁用循环引用

5.7 创建bean

(1) 如果是单例则需要首先清除缓存(2) 实例化bean,将BeanDefinition转换为BeanWrapper(3) MergedBeanDefinitionPostProccessor的应用(4) 依赖处理(5) 属性填充(6) 循环依赖检查(7) 注册DisposableBean(8) 完成创建并返回protected Object doCreateBean(final String beanName, final RooBeanDefinition mbd, final Object[] args) {    BeanWrapper instanceWrapper = null;    // 如果是单例则需要首先清除缓存    if (mbd.isSingleton()) {        instanceWrapper = this.factoryBeanObjectCache.remove(beanName);    }    // 实例化bean,将BeanDefinition转换为BeanWrapper    if (instanceWrapper == null) {        instanceWrapper = createBeanInstance(beanName, mbd, args);    }    final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);    Class beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);    // MergedBeanDefinitionPostProccessor的应用    synchronized (mbd.postProcessingLock) {        if (!mbd.postProcessed) {            applyMergedBeanDefinitionPostProccessor(mbd, beanType, beanName);        }    }    // 依赖处理    // 是否需要提前暴露(单例&循环引用&当前bean正在创建中)    boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences && isSingletongCurrentlyInCreation(beanName));    if (earlySingletonExposure) {        // 为避免循环依赖,在bean初始化完成前将创建实例的ObjectFactory加入工厂        addSingletonFactory(beanName, new ObjectFactory(){            public Object getObject() throw e {                // 对bean的再一次依赖引用                return getEarlyBeanReferences(beanName, mbd, bean);            }        });    }        Object exposedObject = bean;    // 属性填充    try {        populateBean(beanName, mbd, instanceWrapper);        if (exposedObject != null) {            // 调用初始化方法,init-method            exposedObject = initializeBean(beanName, exposedObject, mbd);        }    } catch (e) {        throw e;    }        // 循环依赖检查    if (earlySingletonExposure) {        Object earlySingletonReference = getSingleton(beanName, false);        if (earlySingletonReference != null) {            // exposedObject没有在初始化方法改变,说明没有被增强            if (exposedObject == null) {                exposedObject = earlySingletonReference;            } else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {                String[] dependentBeans = getDependentBeans(beanName);                Set
actualDependentBeans = new LinkedHashSet
(); for (String dependentBean : dependentBean) { // 检测依赖 if (!removeSingletonIfCreateForTypeCheckOnly(dependentBean)) { actualDependentBeans.add(dependentBean); } } if (!actualDependentBeans.isEmpty()) { throw e; } } } } // 注册DisposableBean try { registerDisposableBeanIfNecessary(beanName, bean, mbd); } catch (e) { throw e; } return exposedObject;}

5.7.1.1 属性的注入

(1) InstantiationAwareBeanPostProcessor处理器的postProcessAfterInstantiation函数的应用,此函数可以控制程序是否继续进行属性填充(2) 根据类型,提取依赖bean,并统一存入PropertyValues中。(3) 应用InstantiationAwareBeanPostProcessor处理器的postProcessPropertyValues方法,对属性获取完毕填充前对属性的再次处理,RequiredAnnotationBeanPostProcessor对属性的验证(4) 将所有PropertyValues中的属性填充至BeanWrapper中populateBean(beanName, mbd, bw) {    PropertyValues pvs = mbd.getPropertyValues();    if (bw == null) {        if (!pvs.isEmpty()) {            throw e;        } else {            // 没有属性填充            return ;        }    }        boolean continueWithPropertyPopulation = true;    for (BeanPostProcessor bp : getBeanPostProcessors()) {        if (bp instanceof InstantiationAwareBeanPostProcessor) {            InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;            // 返回值是否继续填充bean            if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {                continueWithPropertyPopulation = false;                break;            }        }    }    // 如果后处理器发出停止填充命令则终止后续的执行    if (!continueWithPropertyPopulation) {        return;    }        if (mbd.getResolvedAutowireMode() == RooBeanDefinition.AUTOWIRE_BY_NAME ||             mbd.getResolvedAutowireMode() == RooBeanDefinition.AUTOWIRE_BY_TYPE) {        MutablePropertyValues newPvs = new MutablePropertyValues(pvs);        if (mbd.getResolvedAutowireMode() == RooBeanDefinition.AUTOWIRE_BY_NAME) {            autowireByName(beanName, mbd, bw, newPvs);        }        if (mbd.getResolvedAutowireMode() == RooBeanDefinition.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 = filterPropertyDescriptionsForDependencyCheck(bw);        if (hasInstAwareBpps) {            for (BeanPostProcessor bp : getBeanPostProcessors()) {                InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;                // 对所有需要依赖检查的属性进行后处理                pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);                if (pvs == null) {                    return;                }            }        }         if (needsDepCheck) {            checkDependences(beanName, mbd, filteredPds, pvs);        }    }    // 将属性应用到bean中    applyPropertyValues(beanName, mbd, bw, pvs);}// 根据name注入属性autowireByName(beanName, mbd, bw, newPvs) {    String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);    for (String propertyName : propertyNames) {        if (containsBean(propertyName)) {            // 递归初始化相关的bean            Object bean = getBean(propertyName);            pvs.add(propertyName, bean);            // 注册依赖            registerDependentBean(propertyName, beanName);        } else {            if (logger.isTraceEnabled()) {                logger.trace(...);            }        }    }}// 根据type注入属性autowireByType(beanName, mbd, BeanWrapper bw, newPvs) {    try {        TypeConverter converter = getCustomTypeConverter();        if (converter == null) {            converter = bw;        }                Set
autowiredBeanNames = new LinkedHashSet
(4); // 寻找bw中需要依赖注入的属性 String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw); for (String propertyName : propertyNames) { PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName); if (!Object.calss.equals(pd.getProperType())) { // 探测指定的set方法 MethodParamter methodParam = BeanUtils.getWriteMethodParamter(pd); boolean eager = PriorityOrdered.class.isAssignableFrom(bw.getWrappedClass()); PropertyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager); // 解析指定的属性所匹配的值,并把解析到的属性的名称存储在autowiredBeanNames中,当属性存在多个封装bean时: // @Autowired private List
aList; 将会找到所有匹配A类型的bean将其注入 Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter); if (autowiredArgument != null) { pvs.add(propertyName, autowiredArgument); } for (String autowiredBeanName : autowiredBeanNames) { // 注册依赖 registerBeanDefinition(autowiredBeanName, beanName); } autowiredBeanNames.clear(); } } } catch (e) { throw e; }}resolveDependency(descriptor, beanName, Set
autowiredBeanNames, typeConverter) { descriptor.initParamterNameDisconvery(getParamterNameDisconverer()); // ObjectFactory类注入的特殊处理 if (descriptor.getDependencyType().equals(ObjectFactory.class)) { return new DependencyObjectFactory(descriptor, beanName); } else if (... eq javaxInjectProviderClass) { return new DependencyObjectFactory().createDependencyProvider(descriptor, beanName); } else { // 通用逻辑处理 return doResolvedDependency(descriptor, descriptor.getDependencyType(), beanName, autowiredBeanNames, typeConverter); }}doResolvedDependency(descriptor, descriptor.getDependencyType(), beanName, autowiredBeanNames, typeConverter) { // 用于支持spring中新增的注解@value Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor); if (value != null) { if (value instanceof String) { value = evaluateBeanDefinitionString(strVal, bd); } TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter()); return converter.convertIfNecessary(value, type); } // 属性是数组类型 if (type.isArray()) { // 数组类型 Class
componentType = type.getComponentType(); Map
matchingBeans = findAutowireCandidates(beanName, componentType, descriptor); if (matchingBeans.isEmpty()) { if (descriptor.isRequired()) { raiseNoSuchBeanDefinitionException(componentType, componentType.getName(), descriptor); } return null; } if (autowiredBeanNames != null) { autowiredBeanNames.addAll(matchingBeans.keySet()); } TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter()); return converter.convertIfNecessary(matchingBeans.values(), type); } else if (Collection.class.isAssignableFrom(type) && type.isInterface()) { // 集合类型 Class
elementType = descriptor.getCollectionType(); if (elementType == null) { if (descriptor.isRequired()) { throw e; } return null; } Map
matchingBeans = findAutowireCandidates(beanName, componentType, descriptor); if (matchingBeans.isEmpty()) { throw e; } if (autowiredBeanNames != null) { autowiredBeanNames.addAll(matchingBeans.keySet()); } TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter()); return converter.convertIfNecessary(matchingBeans.values(), type); } else if (Map.class.isAssignableFrom(type) && type.isInterface()) { // Map类型 Class
keyType = descriptor.getMapKeyType(); if (keyType == null) { if (descriptor.isRequired()) { throw e; } return null; } Map
matchingBeans = findAutowireCandidates(beanName, componentType, descriptor); if (matchingBeans.isEmpty()) { throw e; } if (autowiredBeanNames != null) { autowiredBeanNames.addAll(matchingBeans.keySet()); } TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter()); return converter.convertIfNecessary(matchingBeans.values(), type); } else { Map
matchingBeans = findAutowireCandidates(beanName, componentType, descriptor); if (matchingBeans.isEmpty()) { throw e; } if (matchingBeans.size() > 1) { String primaryBeanName = determinePrimaryCandidate(matchingBeans, descriptor); if (primaryBeanName == null) { throw e; } if (autowiredBeanNames != null) { autowiredBeanNames.add(primaryBeanName); } return matchingBeans.get(primaryBeanName); } // 已经可以确定只有一个匹配项 Map.Entry
entry = matchingBeans.entrySet().iterator().next(); if (autowiredBeanNames != null) { autowiredBeanNames.add(entry.getKey()); } return entry.getValue(); }}// 将属性应用到bean中applyPropertyValues(beanName, mbd, bw, pvs) { if (pvs == null || pvs.isEmpty()) { return; } MutablePropertyValues mpvs = null; List
original; if (bw instancof BeanWrapperImpl) { ((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext()); } if (pvs instanceof MutablePropertyValues) { mpvs = (MutablePropertyValues) pvs; // 如果mpvs中的值已经被转换为对应的类型那么可以直接设置到beanWrapper中 try { if (mpvs.isConverted()) { bw.setPropertyValues(mpvs); return; } } catch (e) { throw e; } original = mpvs.getPropertyValueList(); } else { // 非MutablePropertyValues封装的类型,那么直接使用原始的属性获取方法 original = Arrays.asList(pvs.getPropertyValues()); } TypeConverter converter = getCustomTypeConverter(); if (converter == null) { converter = bw; } // 获取对应的解析器 BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter); // Create a deep copy, resolving any references for values. List
deepCopy = new ArrayList
(original.size()); boolean resolveNecessary = false; for (PropertyValue pv : original) { if (pv.isConverted()) { deepCopy.add(pv); } else { String propertyName = pd.getName(); Object originalValue = pd.getValue(); Object resolvedValue = valueResolver.resolveValueIfNecessay(pv, originalValue); Object convertedValue = resolvedValue; boolean convertible = (bw.isWritableProperty(propertyName) && !PropertyUtils.isNestedIndexedProperty(propertyName)); if (convertible) { convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter); } if (convertedValue == originalValue) { if (convertible) { pv.setConvertedValue(convertedValue); } deepCopy.add(pv); } else if (convertible && originalValue instanceof TypedStringValue && !((TypedStringValue) originalValue).isDynamic() && !(convertedValue instanceof Collection || ObjectUtils.isArray(convertedValue))){ pv.setConvertedValue(convertedValue); deepCopy.add(pv); } else { resolveNecessary = true; deepCopy.add(new PropertyValue(pv, convertedValue)); } } } if (mpvs != null && !resolveNecessary) { mpvs.setConverted(); } try { bw.setPropertyValues(new MutablePropertyValues(deepCopy)); } catch (e) { throw e; }}

5.7.2 初始化bean

// spring容器已经执行过bean的实例化,并且进行了属性填充,而就是这时将会调用用户设定的初始化方法initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {    if (System.getSecurityMananger() != null) {        AccessController.doPrivileged(new PrivilegedAction(){            Object run() {                invokeAwareMethods(beanName, bean);                return null;            }        });    } else {        // 对特殊的bean处理:Aware、BeanClassLoaderAware、BeanFactoryAware        invokeAwareMethods(beanName, bean);    }        Object wrappedBean = bean;    if (mbd != null || !mbd.isSynthetic()) {        // 应用前处理器        wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);    }    try {        // 激活用户自定义的init方法        invokeInitMethod(beanName, wrappedBean, mbd);    } catch (e) {        throw e;    }    if (mbd != null || !mbd.isSynthetic()) {        // 后处理器应用        wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);    }    return wrappedBean;}invokeAwareMethods(final String beanName, final Object bean) {    if (bean instanceof Aware) {        if (bean instanceof BeanNameAware) {            ((BeanNameAware) bean).setBeanName(beanName);        }        if (bean instanceof BeanClassLoaderAware) {            ((BeanClassLoaderAware) bean).setBeanClassLoader(getBeanClassLoader());        }        if (bean instanceof BeanFactoryAware) {            ((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);        }    }}// 处理器应用applyBeanPostProcessorsBeforeInitialization(existingBean, beanName) {    Object result = existingBean;    for ( BeanPostProcessor beanProcessor : getBeanPostProcessors()) {        result = beanProcessor.postProcessBeforeInitialization(result, beanName);        if (result == null) {            return result;        }    }    return result;}applyBeanPostProcessorsAfterInitialization(existingBean, beanName) {    Object result = existingBean;    for ( BeanPostProcessor beanProcessor : getBeanPostProcessors()) {        result = beanProcessor.postProcessAfterInitialization(result, beanName);        if (result == null) {            return result;        }    }    return result;}// 激活用户自定义的init方法invokeInitMethod(beanName, bean, mbd) {    // 检查是否是InitializingBean,如果是则调用afterPropertiesSet方法    boolean isInitializingBean = (bean istanceof InitializingBean);    if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {            if (System.getSecurityManager() != null) {            try {                AccessController.doPrivileged(new PrivilegedExceptionAction(){                    Object run() {                        ((InitializingBean) bean).afterPropertiesSet();                        return null;                    }                });            } catch (e) {                throw e;            }        } else {            ((InitializingBean) bean).afterPropertiesSet();        }    }    if (mbd != null) {        String initMethodName = mbd.getInitMethodName();        if (initMethodName != null && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName))            && !mbd.isExternallyManagedInitMethod(initMethodName)) {            // 调用自定义初始化方法            invokeCustomInitMethod(beanName, bean, mbd);        }    }}

5.7.3 注册DisposableBean

protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {    AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);    if (!mbd.isPrototype() && requiredDestruction(bean, mbd)) {        if (mbd.isSingleton()) {            // 单例模式下需要注册需要销毁的bean,此方法中会处理实现DisposableBean的bean,            // 并且对所有的bean使用DestrunctionAwareBeanPostProccessors处理            // DisposableBean DestrunctionAwareBeanPostProccessors            registerDisposableBean(beanName, new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));        } else {            scope scope = this.scopes.get(mgd.getScope());            if (scope == null) {                throw e;            }            scope.registerDestructionCallback(beanName, new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));        }    }}

6. 容器的功能扩展

ApplicationContext,用于扩展BeanFactory现有功能。

  使用场景:
   ApplicationContext ctx = new ClassPathXmlApplicationContext("beanFactoryTest.xml");

|-- ClassPathXmlApplicationContext(String configLoocation) {                this(new String[]{configLocation}, true, null);            }        |-- ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent) {                super(parent);                setConfigLocations(configLocations);                if (refresh) {                    refresh();                }            }        |-- 6.1 设置路径            |-- setConfigLocations(String[] locations) {                    if (locations != null) {                        this.locations = new String[locations.length];                        for (i=0 ; i
|-- applyPropertyValues --> BeanDefinitionValueResolver valueResolver --> evluateBeanDefinitionString(String value, BeanDefinition beanDefinition) { if (this.beanExpressionResolver == null) { return value; } scope = (beanDefinition != null ? getRegisteredScope(beanDefinition.getScope()) : null); return this.beanExpressionResolver.evaluate(value, new BeanExpressionContext(this, scope)); } |-- 6.5.2 增加对属性编辑器的支持 |--
2013-03-15
|-- 直接使用会报错,如下: UserManager userManager = ctx.getBean(userManager); sysout(userManager); |-- 方案1:使用自定义属性编辑器 |-- DatePropertyEditor extends PropertyEditorSupport { private String format = "yyyy-MM-dd"; void setFormate(String format) { this.format = format; } @Override public void setAsText(String args0) throw e { SimpleDateFormat sdf = new SimpleDateFormat(format); try { Date d = sdf.parse(args0); this.setValue(d); } catch (e) { throw e; } } } |-- 将自定义编辑器注册到Spring中 |--
|-- 方案2:使用Spring自带的属性编辑器CustomDateEditor |-- (1) 定义属性编辑器 |-- DatePropertyEditorRegistrar implements PropertyEditorRegistrar { registerCustomEditors(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true)); } |-- (2) 注册到Spring中 |--
|-- registerCustomEditors(PropertyEditorRegistrar registry) { ResourceEditor baseEditor = new ResourceEditor(this.resourceLoader, this.propertyResolver); doRegisterEditor(registry, Resource.class, baseEditor); doRegisterEditor(registry, ContextResource.class, baseEditor); doRegisterEditor(registry, InputStream.class, new InputStremEditor(baseEditor)); doRegisterEditor(registry, InputSource.class, new InputSourceEditor(baseEditor)); doRegisterEditor(registry, File.class, new FileEditor(baseEditor)); doRegisterEditor(registry, URL.class, new URLEditor(baseEditor)); ClassLoader classLoader = this.resourceLoader.getClassLoader(); doRegisterEditor(registry, URI.class, new URIEditor(classLoader)); doRegisterEditor(registry, Class.class, new ClassEditor(classLoader)); doRegisterEditor(registry, Class[].class, new ClassArrayEditor(classLoader)); if (this.resourceLoader instanceof ResourcePatternResolver) { doRegisterEditor(registry, Resource[].class, new ResourceArrayPropertyEditor((ResourcePatternResolver) this.resourceLoader, this.propertyResolver)); } } doRegisterEditor(PropertyEditorRegistrar registry, Class
requiredType, PropertyEditor editor) { if (registry instanceof PropertyEditorRegistrySupport) { ((PropertyEditorRegistrySupport) registry).overrideDefaultEditor(requiredType, editor); } else { registry.registerCustomEditors(requiredType, editor); } } |-- BeanWrapperImpl implements BeanWrapper extends PropertyEditorRegistrySupport { createDefaultEditors() { this.defaultEditors = new HashMap
, PropertyEditor>(64); this.defaultEditors.put(Charset.class, new CharsetEditor()); this.defaultEditors.put(Class.class, new ClassEditor()); ... } } |-- 6.5.3 添加ApplicationContextAwareProcessor处理器 |-- prepareBeanFactory() --> beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this)) // 注册个BeanPostProcessor,而真正的逻辑在ApplicationContextAwareProcessor中 --> ApplicationContextAwareProcessor implements BeanPostProcessor { // spring激活bean的init-method方法前后,会调用BeanPostProcessor的postProcessorBeforeInitailization()方法和postProcessAfterInitailization()方法 // 同样对ApplicationContextAwareProcessor我们也关心这两个方法 Object postProcessorBeforeInitailization(Object bean, String beanName) { return bean; } Object postProcessAfterInitailization(final Object bean, String beanName) { AccessController acc = null; if (System.getSecurityManager() != null && (bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware || bean instanceof ResourceLoaderAware || bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware)) { acc = this.applicationContext.getBeanFactory().getAccessControlContext(); } if (acc != null) { AccessController.doPrivileged(new PrivilegedAction
(){ public Object run() { invokeAwareInterfaces(bean); return null; } }); } else { invokeAwareInterfaces(bean); } return bean; } invokeAwareInterfaces(Object bean) { if (bean instanceof Aware) { if (bean instance of EnvironmentAware) { ((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment()); } if (bean instance of EmbeddedValueResolverAware) { ((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(new EmbeddedValueResolver(this.applicationContext.getBeanFactory())); } if (bean instance of EnvironmentAware) { ((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment()); } if (bean instance of ResourceLoaderAware) { ((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext); } if (bean instance of ApplicationContextAware) { ((ApplicationContextAware) bean).setApplicationContextContext(this.applicationContext); } ... } } } |-- 6.5.4 设置忽略属性 beanFactory.ingoreDependencyInterface(ResourceLoaderAware.class); beanFactory.ingoreDependencyInterface(ApplicationEventPulisherAware.class); beanFactory.ingoreDependencyInterface(MessageSourceAware.class); beanFactory.ingoreDependencyInterface(ApplicationContextAware.class); beanFactory.ingoreDependencyInterface(EnvironmentAware.class); |-- 6.5.5 注册依赖 beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory); beanFactory.registerResolvableDependency(ResourceLoader.class, beanFactory); beanFactory.registerResolvableDependency(ApplicationEventPulisher.class, beanFactory); beanFactory.registerResolvableDependency(ApplicationContext.class, beanFactory); |-- 6.6 BeanFactory 的后处理 |-- 6.6.1 激活注册的BeanFactoryPostProcessor |-- (1) BeanFactoryPostProcessor的典型应用: |--
${bean.message}
|-- bean.properties bean.message=Hi, can you find me? |-- 配置信息:
config/bean.properties
|-- PropertyPlaceholderConfigurer 间接继承了BeanFactoryPostProcessor |-- (2) 使用自定义BeanFactoryPostProcessor |--
bollocks
winky
bum
Microsoft
... |-- ObscenityRemovingBeanFactoryPostProcessor implements BeanFactoryPostProcessor { private Set
obscenties; ObscenityRemovingBeanFactoryPostProcessor() { obscenties = new HashSet
(); } void postProcessBeanFactory(beanFactory) { String[] beanNames = beanFactory.getBeanDefinitionNames(); for (String beanName : beanNames) { BeanDefinition bd = beanFactory.getBeanDefinition(beanName); StringValueResolver valueREsolver = new StringValueResolver(){ String resolveStringValue(String strVal) { if (isObscene(strVal)) return "*****"; return strVal; } }; BeanDefinitionVisitor vistor = new BeanDefinitionVisitor(valueResolver); visitor.visitBeanDefinition(bd); } } boolean isObscene(Object value) { String potentialObscenity = value.toString().toUppercase(); return this.obscenties.contains(); } void setObscenties(Set
obscenties) { this.obscenties.clear(); for(String obscenity : obscenties) { this.obscenties.add(obscenity.toUpperCase()); } } } // 执行类: public class PropertyConfigurerDemo { main(String[] args) { bf = new XmlBeanFactory(new ClassPathResource("/META-INF/BeanFactory.xml")); ObscenityRemovingBeanFactoryPostProcessor bfpp = (ObscenityRemovingBeanFactoryPostProcessor) bf.get("bfpp"); bfpp.postProcessBeanFactory(bf); sysout(bf.getBean("simpleBean")); // 输出结果:SimplePostProcessor{connectionString=*****,username=*****,password=imaginecup} } } |-- 激活BeanFactoryPostProcessor (1) 对于硬编码注册的后处理器的处理,主要通过AbstractApplicationContext中的添加处理器方法addBeanFactoryPostProcessor (2) 记录后处理器主要使用了三个List完成 registryPostProcessors:记录通过硬编码方式注册的BeanDefinitionRegistryPostProcessor类型处理器 regularPostProcessors:记录通过硬编码方式注册的BeanFactoryPostProcessors registryPostProcessorBeans:记录通过硬编码方式注册的BeanDefinitionRegistryPostProcessor (3) 对以上所记录的List中的后处理器进行统一调用beanFactoryPostProcessors的postProcessBeanFactory() (4) 对beanFactoryPostProcessors中非BeanDefinitionRegistryPostProcessor类的后处理器进行统一调用beanFactoryPostProcessors的postProcessBeanFactory() (5) 普通beanFactory处理 |-- invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) { // BeanDefinitionRegistry if (beanFactory instanceof BeanDefinitionRegistry) { BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory; // for (BeanFactoryPostProcessor postProcessor :getBeanFactoryPostProcessors()) { if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) { registryPostProcessor = (BeanDefinitionRegistryPostProcessor) postProcessor; // 对于BeanDefinitionRegistryPostProcessor类型,在BeanFactoryPostProcessor基础上还有自己定义的方法,需要先调用 registryPostProcessor.postProcessBeanDefinitionRegistry(registry); registryPostProcessors.add(registryPostProcessor); } else { regularPostProcessors.add(postProcessor); } } // 配置注册的后处理器 Map
beanMap = beannFactory.getBeanOfType(BeanDefinitionRegistryPostProcessor.class, true, false); List
registryPostProcessorBeans = new ArrayList<>(beanMap.values()); for (BeanDefinitionRegistryPostProcessor postProcessor : registryPostProcessorBeans) { postProcessor.postProcessBeanDefinitionRegistry(registry); } // invokeBeanFactoryPostProcessors(registryPostProcessors, beanFactory); invokeBeanFactoryPostProcessors(registryPostProcessorBeans, beanFactory); invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory); } else { invokeBeanFactoryPostProcessors(getBeanFactoryPostProcessors(), beanFactory); } // 从配置文件中读取的BeanFactoryPostProcessor的处理 String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false); List
priorityOrderedPostProcessors = new ArrayList<>(); List
orderedPostProcessorNames = new ArrayList<>(); List
nonOrderedPostProcessorNames = new ArrayList<>(); // 对后处理器分类处理 for (String ppName : postProcessorNames) { if (processedBeans..contains(ppName)) { // 已经处理过的 } else if (isMatch(ppName, PriorityOrdered.class)) { priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class)); } else if (isMatch(ppName, Ordered.class)) { orderedPostProcessorNames.add(ppName); } else { nonOrderedPostProcessorNames.add(ppName); } } // 按优先级排序 OrderComparator.sort(priorityOrderedPostProcessors); invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory); // next, invoke the List
orderedPostProcessors = new ArrayList<>(); for (String postProcessorName : orderedPostProcessorNames) { orderedPostProcessors.add(getBean(postProcessorName, BeanFactoryPostProcessor.class)); } OrderComparator.sort(orderedPostProcessors); invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory); // 无序直接调用 List
nonOrderedPostProcessors = new ArrayList<>(); for (String postProcessorName : nonOrderedPostProcessorNames) { nonOrderedPostProcessors.add(getBean(postProcessorName, BeanFactoryPostProcessor.class)); } invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory); } |-- 6.6.2 注册BeanPostProcessor |-- 自动注册功能 |-- MyInstantiationAwareBeanPostProcessor implements InstantiationAwareBeanPostProcessor { Object postProcessBeforeInitailization(Object bean, String beanName) { sysout("=============="); return null; } } |--
|-- ApplicationContext ctx ; -> ctx.get("xxBean") -> sysout("=============="); |-- 上面这个特性是在registerBeanPostProcessors方法中完成的 |-- protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) { // 从配置文件中读取的BeanFactoryPostProcessor的处理 String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false); int beanPostTargetProcessorCount = beanFactory.getBeanPostProcessorCount(); beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanPostTargetProcessorCount)); // 使用PriorityOrdered保证顺序 List
priorityOrderedPostProcessors = new ArrayList<>(); // List
internalPostProcessor = new ArrayList<>(); // 使用Ordered保证顺序 List
orderedPostProcessorNames = new ArrayList<>(); // 无序 List
nonOrderedPostProcessorNames = new ArrayList<>(); // 对后处理器分类处理 for (String ppName : postProcessorNames) { if (isMatch(ppName, PriorityOrdered.class)) { BeanFactoryPostProcessor pp = beanFactory.getBean(ppName, BeanFactoryPostProcessor.class); priorityOrderedPostProcessors.add(pp); if (pp instanceof MergedBeanDefinitionPostProccessor) { internalPostProcessor.add(pp); } } else if (isMatch(ppName, Ordered.class)) { orderedPostProcessorNames.add(ppName); } else { nonOrderedPostProcessorNames.add(ppName); } } // 按优先级排序 OrderComparator.sort(priorityOrderedPostProcessors); registerBeanFactoryPostProcessors(beanFactory, priorityOrderedPostProcessors); // next, invoke the List
orderedPostProcessors = new ArrayList<>(); for (String postProcessorName : orderedPostProcessorNames) { BeanFactoryPostProcessor pp = beanFactory.getBean(ppName, BeanFactoryPostProcessor.class); orderedPostProcessors.add(pp); if (pp instanceof MergedBeanDefinitionPostProccessor) { internalPostProcessor.add(pp); } } OrderComparator.sort(orderedPostProcessors); registerBeanFactoryPostProcessors(beanFactory, orderedPostProcessors); // 无序直接调用 List
nonOrderedPostProcessors = new ArrayList<>(); for (String postProcessorName : nonOrderedPostProcessorNames) { BeanFactoryPostProcessor pp = beanFactory.getBean(ppName, BeanFactoryPostProcessor.class); nonOrderedPostProcessors.add(pp); if (pp instanceof MergedBeanDefinitionPostProccessor) { internalPostProcessor.add(pp); } } registerBeanFactoryPostProcessors(beanFactory, nonOrderedPostProcessors); // 注册所有的MergedBeanDefinitionPostProccessor类型的BeanPostProcessor OrderComparator.sort(internalPostProcessor); registerBeanFactoryPostProcessors(beanFactory, internalPostProcessor); // 添加ApplicationListener探测器 beanFactory.addBeanPostProcessor(new ApplicationListenerDetector()); } |-- 6.6.3 初始化消息资源 |-- 示例: (1) Locale locale1 = new Locale("zh","CN"); // 带语言+国家/地区信息的 (2) Locale locale2 = new Locale("zh"); // 带语言 (3) Locale locale3 = Locale.CHINA; // 带语言+国家/地区信息的 (4) Locale locale4 = Locale.CHINESS; // 带语言 (5) Locale locale5 = Locale.getDefault(); // 系统默认的本地化对象 pattern1 = "{0} hello!"; pattern2 = "{0} 你好!"; Object[] params = { "John"}; // 默认言语格式化 String msg1 = MessageFormat.format(pattern1, params); // 指定言语格式化 MessageFormat mf = new MessageFormat(pattern2, Locale.US); String msg2 = mf.format(params); |-- 如果使用 (1) 定义资源文件 |-- messages.properties test=test |-- messages_zh_CN.properties test=测试 (2) 定义配置文件(id必须为messageSource)
test/messages
(3) 使用。 String[] configs = { "applicationContext.xml"}; Application ctx = new ClassPathXmlApplicationContext(configs); Object[] params = { "John"}; String str1 = ctx.getMessage("test", params, Locale.US); String str2 = ctx.getMessage("test", params, Locale.CHINA); |-- 核心方法: protected void initMessageSource() { beanFactory = getBeanFactory(); if (beanFactory.containsLocalBean(MESSAGE_SOURCE_NAME)) { this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_NAME, MessageSource.class); if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) { HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource; if (hms.getParentMessageSource() == null) { hms.setParentMessageSource(getInteralParentMessageSource()); } } } else { DelegatingMessageSource dms = new DelegatingMessageSource(); dms.setParentMessageSource(getInteralParentMessageSource()); this.messageSource = dms; beanFactory.registerSingleton(MESSAGE_SOURCE_NAME, this.messageSource); logger.info(...); } } getMessage(String code, Object[] args, Locale locale) { return getMessageSource().getMessage(code, args, locale); } |-- 6.6.4 初始化ApplicationEventMulticaster |-- (1) 定义监听事件 |-- TestEvent extends ApplicationEvent { String msg; TestEvent(Object source) { super(source); } TestEvent(Object source, String msg) { super(source); this.msg = msg; } print() { sysout(msg); } } |-- (2) 定义监听器 |-- TestListener implements ApplicationListener { onApplicationEvent(ApplicationEvent event) { if (event instanceof TestEvent) { TestEvent testEvent = (TestEvent) event; testEvent.print(); } } } |-- (3) 添加配置文件
|-- (4) 测试 Test { main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); TestEvent event = new TestEvent("hello", "msg"); context.publishEvent(event); } } |-- 初始化ApplicationEventMulticaster |-- initApplicationEventMulticaster() { beanFactory = getBeanFactory(); if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) { this.applicationEventMulticaster = beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class); if (logger.isDebugEnable()) { logger.info(...); } } else { this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory); beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster); if (logger.isDebugEnable()) { logger.info(...); } } } |-- SimpleApplicationEventMulticaster { public void multicastEvent(final ApplicationEvent event) { for ( ApplicationListener listener : getApplicationListeners()) { Executor executor = getTaskExecutor(); if (executor != null) { executor.execute(new Runnable(){ run() { listener.onApplicationEvent(event); } }); } else { listener.onApplicationEvent(event); } } } } |-- 6.6.5 注册监听器 |-- protected void registerListeners() { for (ApplicationListener listener : getApplicationListeners()) { getApplicationEventMulticaster().addApplicationListener(listener); } // 配置文件注册的监听器处理 String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false); for (String listName : listenerBeanNames) { getApplicationEventMulticaster().addApplicationListenerBean(listName); } } |-- 6.7 初始化非延迟加载单例 |-- protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) { // InitializingBean 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)); } // InitializingBean LoadTimeWeaverAwareProcessor beans early to allow for registering their transformedBeanName 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定义,说明注册的bean定义将不被修改或任何进一步的处理 }待续。。。

 

转载于:https://www.cnblogs.com/ice-line/p/9590842.html

你可能感兴趣的文章
进击吧!阶乘——大数乘法
查看>>
安卓学习资料推荐-25
查看>>
Mysql数据库备份和还原常用的命令
查看>>
关于退出当前页面在火狐的一些问题
查看>>
【项目实施】项目考核标准
查看>>
spring-aop AnnotationAwareAspectJAutoProxyCreator类
查看>>
经典入门_排序
查看>>
Redis Cluster高可用集群在线迁移操作记录【转】
查看>>
二、spring中装配bean
查看>>
VIM工具
查看>>
javascript闭包
查看>>
@Column标记持久化详细说明
查看>>
创建本地yum软件源,为本地Package安装Cloudera Manager、Cloudera Hadoop及Impala做准备...
查看>>
mysql8.0.13下载与安装图文教程
查看>>
站立会议08(冲刺2)
查看>>
url查询参数解析
查看>>
http://coolshell.cn/articles/10910.html
查看>>
[转]jsbsim基础概念
查看>>
DIV和SPAN的区别
查看>>
第一次使用cnblogs
查看>>