Spring源码-IOC(三)
来源:互联网 发布:淘宝网店宝贝图片尺寸 编辑:程序博客网 时间:2024/06/06 17:06
Spring源码-IOC
springmvc项目启动入口位置是:web.xml中配置的listener。
在web.xml配置这个监听器,启动容器时,就会默认执行它实现的方法。在ContextLoaderListener中关联了ContextLoader这个类,所以整个加载配置过程由ContextLoader来完成。
//初始化web应用上下文方法:ContextLoader中的initWebApplicationContext方法public WebApplicationContext initWebApplicationContext(ServletContext servletContext) { //判断web用用根上下文是否已经存在:如果存在则抛出异常,这么做是为了防止重复加载 if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) { throw new IllegalStateException( "Cannot initialize context because there is already a root application context present - " + "check whether you have multiple ContextLoader* definitions in your web.xml!"); } Log logger = LogFactory.getLog(ContextLoader.class); servletContext.log("Initializing Spring root WebApplicationContext"); if (logger.isInfoEnabled()) { logger.info("Root WebApplicationContext: initialization started"); } long startTime = System.currentTimeMillis(); try { // Store context in local instance variable, to guarantee that // it is available on ServletContext shutdown. //类在实例属性变量里存储上下文信息,为了保证在Servlet上下文关闭的时候可以使用 if (this.context == null) { //创建上下文信息:返回的是:在开发人员没有配置的情况下返回Congtext.properties中配置的默认XmlWebApplicationContext对象的实例 this.context = createWebApplicationContext(servletContext); } //判断获取到上下文是否为ConfigurableWebApplicationContext的实例(子类的实例:XmlWebApplicationContext) if (this.context instanceof ConfigurableWebApplicationContext) { ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context; //判断应用上下文是否已经激活,如果未激活:设置父上下文信息 if (!cwac.isActive()) { // The context has not yet been refreshed -> provide services such as // setting the parent context, setting the application context id, etc if (cwac.getParent() == null) { // The context instance was injected without an explicit parent -> // determine parent for root web application context, if any. ApplicationContext parent = loadParentContext(servletContext); cwac.setParent(parent); } //重点:配置及刷新web应用上下文信息 configureAndRefreshWebApplicationContext(cwac, servletContext); } } //设置根向下文信息 servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context); //获取上下文类加载器 ClassLoader ccl = Thread.currentThread().getContextClassLoader(); if (ccl == ContextLoader.class.getClassLoader()) { currentContext = this.context; } else if (ccl != null) { //将类加载器、应用上下文放到ConcurrentHashMap容器中 currentContextPerThread.put(ccl, this.context); } if (logger.isDebugEnabled()) { logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" + WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]"); } if (logger.isInfoEnabled()) { long elapsedTime = System.currentTimeMillis() - startTime; logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms"); } return this.context; } catch (RuntimeException ex) { logger.error("Context initialization failed", ex); servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex); throw ex; } catch (Error err) { logger.error("Context initialization failed", err); servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err); throw err; } } //创建应用上下文 protected WebApplicationContext createWebApplicationContext(ServletContext sc) { Class<?> contextClass = determineContextClass(sc); if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) { throw new ApplicationContextException("Custom context class [" + contextClass.getName() + "] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]"); } return (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass); } //根据配置获取上下文信息Class protected Class<?> determineContextClass(ServletContext servletContext) { //判断是否配置了intitClass String contextClassName = servletContext.getInitParameter(CONTEXT_CLASS_PARAM); if (contextClassName != null) { try { return ClassUtils.forName(contextClassName, ClassUtils.getDefaultClassLoader()); } catch (ClassNotFoundException ex) { throw new ApplicationContextException( "Failed to load custom context class [" + contextClassName + "]", ex); } } else { //默认的:/org/springframework/web/context/ContextLoader.properties中配置的类 contextClassName = defaultStrategies.getProperty(WebApplicationContext.class.getName()); try { return ClassUtils.forName(contextClassName, ContextLoader.class.getClassLoader()); } catch (ClassNotFoundException ex) { throw new ApplicationContextException( "Failed to load default context class [" + contextClassName + "]", ex); } } } //配置及刷新web应用上下文信息 protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) { if (ObjectUtils.identityToString(wac).equals(wac.getId())) { // The application context id is still set to its original default value // -> assign a more useful id based on available information String idParam = sc.getInitParameter(CONTEXT_ID_PARAM); if (idParam != null) { wac.setId(idParam); } else { // Generate default id... wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX + ObjectUtils.getDisplayString(sc.getContextPath())); } } wac.setServletContext(sc); String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM); if (configLocationParam != null) { wac.setConfigLocation(configLocationParam); } // The wac environment's #initPropertySources will be called in any case when the context // is refreshed; do it eagerly here to ensure servlet property sources are in place for // use in any post-processing or initialization that occurs below prior to #refresh ConfigurableEnvironment env = wac.getEnvironment(); if (env instanceof ConfigurableWebEnvironment) { ((ConfigurableWebEnvironment) env).initPropertySources(sc, null); } //定制上下文信息:初始化类等 customizeContext(sc, wac); //重点:bean注册入口 wac.refresh(); } //调用AbstractApplicationContext类的refresh()方法,XmlWebApplicationContext是它的子类 public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { // 加载环境配置信息:配置文件总的占位符等信息初始化 prepareRefresh(); // 获取beanFactory:返回DefaultListableBeanFactory对象 ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); // 为bean工厂添加:处理器,注册器,资源信息注册等 prepareBeanFactory(beanFactory); try { //允许在上下文子类中对bean工厂进行处理:调用XmlWebApplicationContext父类的AbstractRefreshableApplicationContext //postProcessBeanFactory方法,因为方法被AbstractApplicationContext的子类AbstractRefreshableApplicationContext重写 //为bean工厂继续添加bean处理器,并为bean工厂注册beans生命周期及环境信息 postProcessBeanFactory(beanFactory); //开始执行注册到该上下文的BeanFactoryPostProcessors invokeBeanFactoryPostProcessors(beanFactory); // 开始注册BeanPostProcessor来拦截其他的bean的初始化过程 registerBeanPostProcessors(beanFactory); // 初始化消息源 initMessageSource(); //注册上下文事件的广播集 initApplicationEventMulticaster(); //初始化一些特殊的bean onRefresh(); //查询并校验监听器并注册 registerListeners(); // 解析并创建Class对象所有非懒加载的所有bean finishBeanFactoryInitialization(beanFactory); //最后一步发布所有的运用 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(); } } } //获取beanFactory方法 protected ConfigurableListableBeanFactory obtainFreshBeanFactory() { //刷新beanFactory:销毁已经存在的bean信息,关闭已经存在的工厂 //同时开始解析并创建Class对象bean并注册到应用上下文中 refreshBeanFactory();//重点的重点 //创建新的工厂:DefaultListableBeanFactory ConfigurableListableBeanFactory beanFactory = getBeanFactory(); if (logger.isDebugEnabled()) { logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory); } return beanFactory; } //调用XmlWebApplicationContext父类AbstractRefreshableApplicationContext的refreshBeanFactory方法 @Override protected final void refreshBeanFactory() throws BeansException { //销毁已经存在的bean信息,关闭已经存在的工厂 if (hasBeanFactory()) { destroyBeans(); closeBeanFactory(); } try { DefaultListableBeanFactory beanFactory = createBeanFactory(); beanFactory.setSerializationId(getId()); //定制bean工厂:允许bean定义重载,允许循环引用 customizeBeanFactory(beanFactory); //加载定义的bean信息:调用子类XmlWebApplicationContext中的实现loadBeanDefinitions loadBeanDefinitions(beanFactory); synchronized (this.beanFactoryMonitor) { this.beanFactory = beanFactory; } } catch (IOException ex) { throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex); } } //XmlWebApplicationContext:开始解析并创建Class对象bean并注册到应用上下文中 protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException { //通过beanFactory创建XmlBeanDefinitionReader读取器 XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory); // Configure the bean definition reader with this context's // resource loading environment. beanDefinitionReader.setEnvironment(getEnvironment()); beanDefinitionReader.setResourceLoader(this); beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this)); // Allow a subclass to provide custom initialization of the reader, // then proceed with actually loading the bean definitions. //初始化bean定义读取器:空实现 initBeanDefinitionReader(beanDefinitionReader); // loadBeanDefinitions(beanDefinitionReader); } //XmlWebApplicationContext:loadBeanDefinitions(reader) protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws IOException { String[] configLocations = getConfigLocations(); if (configLocations != null) { for (String configLocation : configLocations) { //XmlBeanDefinitionReader的AbstractBeanDefinitionReader父类的loadBeanDefinitions reader.loadBeanDefinitions(configLocation); } } } //AbstractBeanDefinitionReader父类的loadBeanDefinitions public int loadBeanDefinitions(String location) throws BeanDefinitionStoreException { return loadBeanDefinitions(location, null); } //AbstractBeanDefinitionReader父类的重载方法loadBeanDefinitions:加载配置文件信息 public int loadBeanDefinitions(String location, Set<Resource> actualResources) throws BeanDefinitionStoreException { ResourceLoader resourceLoader = getResourceLoader(); if (resourceLoader == null) { throw new BeanDefinitionStoreException( "Cannot import bean definitions from location [" + location + "]: no ResourceLoader available"); } if (resourceLoader instanceof ResourcePatternResolver) { // Resource pattern matching available. try { //多个配置文件加载 Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location); //调用AbstractBeanDefinitionReader的loadBeanDefinitions(resources); int loadCount = loadBeanDefinitions(resources); if (actualResources != null) { for (Resource resource : resources) { actualResources.add(resource); } } if (logger.isDebugEnabled()) { logger.debug("Loaded " + loadCount + " bean definitions from location pattern [" + location + "]"); } return loadCount; } catch (IOException ex) { throw new BeanDefinitionStoreException( "Could not resolve bean definition resource pattern [" + location + "]", ex); } } else { // Can only load single resources by absolute URL. //单个配置文件加载 Resource resource = resourceLoader.getResource(location); //调用XmlBeanDefinitionReader实现BeanDefinitionReader(AbstractBeanDefinitionReader实现了该接口)接口中的loadBeanDefinitions int loadCount = loadBeanDefinitions(resource); if (actualResources != null) { actualResources.add(resource); } if (logger.isDebugEnabled()) { logger.debug("Loaded " + loadCount + " bean definitions from location [" + location + "]"); } return loadCount; } } //调用AbstractBeanDefinitionReader的loadBeanDefinitions(resources); public int loadBeanDefinitions(Resource... resources) throws BeanDefinitionStoreException { Assert.notNull(resources, "Resource array must not be null"); int counter = 0; for (Resource resource : resources) { //循环//调用XmlBeanDefinitionReader实现BeanDefinitionReader(AbstractBeanDefinitionReader实现了该接口)接口中的loadBeanDefinitions counter += loadBeanDefinitions(resource); } return counter; } //XmlBeanDefinitionReader的loadBeanDefinitions(resource); public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException { return loadBeanDefinitions(new EncodedResource(resource)); } //XmlBeanDefinitionReader中的重载方法的loadBeanDefinitions public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException { Assert.notNull(encodedResource, "EncodedResource must not be null"); if (logger.isInfoEnabled()) { logger.info("Loading XML bean definitions from " + encodedResource.getResource()); } Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get(); if (currentResources == null) { currentResources = new HashSet<EncodedResource>(4); this.resourcesCurrentlyBeingLoaded.set(currentResources); } if (!currentResources.add(encodedResource)) { throw new BeanDefinitionStoreException( "Detected cyclic loading of " + encodedResource + " - check your import definitions!"); } try { InputStream inputStream = encodedResource.getResource().getInputStream(); try { InputSource inputSource = new InputSource(inputStream); if (encodedResource.getEncoding() != null) { inputSource.setEncoding(encodedResource.getEncoding()); } //开始加载bean定义信息 return doLoadBeanDefinitions(inputSource, encodedResource.getResource()); } finally { inputStream.close(); } } catch (IOException ex) { throw new BeanDefinitionStoreException( "IOException parsing XML document from " + encodedResource.getResource(), ex); } finally { currentResources.remove(encodedResource); if (currentResources.isEmpty()) { this.resourcesCurrentlyBeingLoaded.remove(); } } } //加载bean定义信息 protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource) throws BeanDefinitionStoreException { try { //获取配置文件的文档对象 Document doc = doLoadDocument(inputSource, resource); //注册bean定义信息:重点 return registerBeanDefinitions(doc, resource); } catch (BeanDefinitionStoreException ex) { throw ex; } catch (SAXParseException ex) { throw new XmlBeanDefinitionStoreException(resource.getDescription(), "Line " + ex.getLineNumber() + " in XML document from " + resource + " is invalid", ex); } catch (SAXException ex) { throw new XmlBeanDefinitionStoreException(resource.getDescription(), "XML document from " + resource + " is invalid", ex); } catch (ParserConfigurationException ex) { throw new BeanDefinitionStoreException(resource.getDescription(), "Parser configuration exception parsing XML from " + resource, ex); } catch (IOException ex) { throw new BeanDefinitionStoreException(resource.getDescription(), "IOException parsing XML document from " + resource, ex); } catch (Throwable ex) { throw new BeanDefinitionStoreException(resource.getDescription(), "Unexpected exception parsing XML document from " + resource, ex); } } //注册bean定义信息:重点 public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException { BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader(); int countBefore = getRegistry().getBeanDefinitionCount(); //通过文档读取器开始读取并注册bean信息 documentReader.registerBeanDefinitions(doc, createReaderContext(resource)); return getRegistry().getBeanDefinitionCount() - countBefore; } //BeanDefinitionDocumentReader的子类DefaultBeanDefinitionDocumentReader的registerBeanDefinitions方法 public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) { this.readerContext = readerContext; logger.debug("Loading bean definitions"); //获取根元素信息 Element root = doc.getDocumentElement(); //注册bean定义信息 doRegisterBeanDefinitions(root); } //DefaultBeanDefinitionDocumentReader的doRegisterBeanDefinitions方法 protected void doRegisterBeanDefinitions(Element root) { //获取父级bean定义解析代理 BeanDefinitionParserDelegate parent = this.delegate; this.delegate = createDelegate(getReaderContext(), root, parent); if (this.delegate.isDefaultNamespace(root)) { String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE); if (StringUtils.hasText(profileSpec)) { String[] specifiedProfiles = StringUtils.tokenizeToStringArray( profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS); if (!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) { if (logger.isInfoEnabled()) { logger.info("Skipped XML bean definition file due to specified profiles [" + profileSpec + "] not matching: " + getReaderContext().getResource()); } return; } } } //xml预处理:空实现 preProcessXml(root); //解析bean定义信息 parseBeanDefinitions(root, this.delegate); postProcessXml(root); this.delegate = parent; } /** * 开始解析bean定义信息:DefaultBeanDefinitionDocumentReader的方法 * Parse the elements at the root level in the document: * "import", "alias", "bean". * @param root the DOM root element of the document */ protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) { //判断是否是beans空间 if (delegate.isDefaultNamespace(root)) { NodeList nl = root.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { Node node = nl.item(i); if (node instanceof Element) { Element ele = (Element) node; if (delegate.isDefaultNamespace(ele)) { //解析:beans下的import,alias,bean,beans元素 parseDefaultElement(ele, delegate); } else { //其他命名空间下的子标签解析:context:component-scan等 delegate.parseCustomElement(ele); } } } } else { //其他命名空间下的子标签解析:context:component-scan等 delegate.parseCustomElement(root); } }//===============================================================非注解bean解析过程开始========================================================= //xml配置类信息解析:开始解析bean定义信息:DefaultBeanDefinitionDocumentReader的parseDefaultElement方法 private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) { if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) { //解析import标签 importBeanDefinitionResource(ele); } else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) { //解析import标签 processAliasRegistration(ele); } else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) { //解析bean标签 processBeanDefinition(ele, delegate); } else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) { //解析嵌套的beans标签 doRegisterBeanDefinitions(ele); } } //非注解:解析bean标签 protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) { //获取bean定义信息 BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele); if (bdHolder != null) { //装饰bean定义信息 bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder); try { // 注册bean BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry()); } catch (BeanDefinitionStoreException ex) { getReaderContext().error("Failed to register bean definition with name '" + bdHolder.getBeanName() + "'", ele, ex); } // Send registration event. getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder)); } } //bean定义解析:BeanDefinitionParserDelegate的parseBeanDefinitionElement方法 public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, BeanDefinition containingBean) { //获取bean id 属性 String id = ele.getAttribute(ID_ATTRIBUTE); //获取bean name 属性 String nameAttr = ele.getAttribute(NAME_ATTRIBUTE); List<String> aliases = new ArrayList<String>(); if (StringUtils.hasLength(nameAttr)) { String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr, MULTI_VALUE_ATTRIBUTE_DELIMITERS); aliases.addAll(Arrays.asList(nameArr)); } String beanName = id; //如果bean id和name属性均为空,则打印日志 if (!StringUtils.hasText(beanName) && !aliases.isEmpty()) { beanName = aliases.remove(0); if (logger.isDebugEnabled()) { logger.debug("No XML 'id' specified - using '" + beanName + "' as bean name and " + aliases + " as aliases"); } } //校验bean id是否唯一,如果不存在则放入usedNames的set集合,否则报错 if (containingBean == null) { checkNameUniqueness(beanName, aliases, ele); } //解析bean的其他属性 AbstractBeanDefinition beanDefinition = parseBeanDefinitionElement(ele, beanName, containingBean); if (beanDefinition != null) { if (!StringUtils.hasText(beanName)) { try { if (containingBean != null) { beanName = BeanDefinitionReaderUtils.generateBeanName( beanDefinition, this.readerContext.getRegistry(), true); } else { beanName = this.readerContext.generateBeanName(beanDefinition); // Register an alias for the plain bean class name, if still possible, // if the generator returned the class name plus a suffix. // This is expected for Spring 1.2/2.0 backwards compatibility. String beanClassName = beanDefinition.getBeanClassName(); if (beanClassName != null && beanName.startsWith(beanClassName) && beanName.length() > beanClassName.length() && !this.readerContext.getRegistry().isBeanNameInUse(beanClassName)) { aliases.add(beanClassName); } } if (logger.isDebugEnabled()) { logger.debug("Neither XML 'id' nor 'name' specified - " + "using generated bean name [" + beanName + "]"); } } catch (Exception ex) { error(ex.getMessage(), ele); return null; } } String[] aliasesArray = StringUtils.toStringArray(aliases); return new BeanDefinitionHolder(beanDefinition, beanName, aliasesArray); } return null; } //非注解bean解析:解析其他属性 public AbstractBeanDefinition parseBeanDefinitionElement( Element ele, String beanName, BeanDefinition containingBean) { //将包含beanName属性的对象放到解析状态的栈中:Stack this.parseState.push(new BeanEntry(beanName)); String className = null; //判断当前bean是否包含class属性 if (ele.hasAttribute(CLASS_ATTRIBUTE)) { className = ele.getAttribute(CLASS_ATTRIBUTE).trim(); } try { String parent = null; //判断当前bean是否包含parent属性 if (ele.hasAttribute(PARENT_ATTRIBUTE)) { parent = ele.getAttribute(PARENT_ATTRIBUTE); } AbstractBeanDefinition bd = createBeanDefinition(className, parent); //解析bean定义的其他属性:singleton,scope,abstract,autowire等 parseBeanDefinitionAttributes(ele, beanName, containingBean, bd); //解析bean的description属性 bd.setDescription(DomUtils.getChildElementValueByTagName(ele, DESCRIPTION_ELEMENT)); //解析bean的meta元素 parseMetaElements(ele, bd); //解析bean的lookup-method属性:方法返回动态加载:特殊的注入方式,很少用到 parseLookupOverrideSubElements(ele, bd.getMethodOverrides()); //解析bean的replaced-method属性:可以在运行时用新的方法替换旧的方法,很少用到 parseReplacedMethodSubElements(ele, bd.getMethodOverrides()); //解析bean的constructor-arg子元素 parseConstructorArgElements(ele, bd); //解析property子元素 parsePropertyElements(ele, bd); //解析qualifier子元素 parseQualifierElements(ele, bd); bd.setResource(this.readerContext.getResource()); bd.setSource(extractSource(ele)); return bd; } catch (ClassNotFoundException ex) { error("Bean class [" + className + "] not found", ele, ex); } catch (NoClassDefFoundError err) { error("Class that bean class [" + className + "] depends on not found", ele, err); } catch (Throwable ex) { error("Unexpected failure during bean definition parsing", ele, ex); } finally { this.parseState.pop(); } return null; } /** * 根据bean的className和parentName创建一个封装了bean class和parent的BeanDefinition对象 * Create a bean definition for the given class name and parent name. * @param className the name of the bean class * @param parentName the name of the bean's parent bean * @return the newly created bean definition * @throws ClassNotFoundException if bean class resolution was attempted but failed */ protected AbstractBeanDefinition createBeanDefinition(String className, String parentName) throws ClassNotFoundException { return BeanDefinitionReaderUtils.createBeanDefinition( parentName, className, this.readerContext.getBeanClassLoader()); } // public static AbstractBeanDefinition createBeanDefinition( String parentName, String className, ClassLoader classLoader) throws ClassNotFoundException { GenericBeanDefinition bd = new GenericBeanDefinition(); bd.setParentName(parentName); if (className != null) { //累加载器不为空:用户自定义类加载器不为空 if (classLoader != null) { //spring的反射工具获取className对应类的的Class对象 bd.setBeanClass(ClassUtils.forName(className, classLoader)); } else { //类加载器为空,说明是(bootstrap:对开发人员屏蔽)根加载器,底层有处理,String对象 bd.setBeanClassName(className); } } return bd; } //===============================================================非注解bean解析过程完毕========================================================= //===============================================================非注解bean注册过程开始========================================================= //BeanDefinitionReaderUtils的静态方法registerBeanDefinition public static void registerBeanDefinition( BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry) throws BeanDefinitionStoreException { // Register bean definition under primary name. String beanName = definitionHolder.getBeanName(); registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition()); // Register aliases for bean name, if any. String[] aliases = definitionHolder.getAliases(); if (aliases != null) { for (String alias : aliases) { registry.registerAlias(beanName, alias); } } } //--------------------------------------------------------------------- // Implementation of BeanDefinitionRegistry interface //----------------------------------BeanDefinitionRegistry的子类DefaultListableBeanFactory ----------------------------------- ///** Map of bean definition objects, keyed by bean name */ //private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<String, BeanDefinition>(256); @Override public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) throws BeanDefinitionStoreException { Assert.hasText(beanName, "Bean name must not be empty"); Assert.notNull(beanDefinition, "BeanDefinition must not be null"); if (beanDefinition instanceof AbstractBeanDefinition) { try { ((AbstractBeanDefinition) beanDefinition).validate(); } catch (BeanDefinitionValidationException ex) { throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName, "Validation of bean definition failed", ex); } } BeanDefinition oldBeanDefinition; //根据当前beanName查看是否已经注册 oldBeanDefinition = this.beanDefinitionMap.get(beanName); if (oldBeanDefinition != null) { //如果bean不允许重载 if (!isAllowBeanDefinitionOverriding()) { throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName, "Cannot register bean definition [" + beanDefinition + "] for bean '" + beanName + "': There is already [" + oldBeanDefinition + "] bound."); } else if (oldBeanDefinition.getRole() < beanDefinition.getRole()) { // e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE if (this.logger.isWarnEnabled()) { this.logger.warn("Overriding user-defined bean definition for bean '" + beanName + "' with a framework-generated bean definition: replacing [" + oldBeanDefinition + "] with [" + beanDefinition + "]"); } } else if (!beanDefinition.equals(oldBeanDefinition)) { if (this.logger.isInfoEnabled()) { this.logger.info("Overriding bean definition for bean '" + beanName + "' with a different definition: replacing [" + oldBeanDefinition + "] with [" + beanDefinition + "]"); } } else { if (this.logger.isDebugEnabled()) { this.logger.debug("Overriding bean definition for bean '" + beanName + "' with an equivalent definition: replacing [" + oldBeanDefinition + "] with [" + beanDefinition + "]"); } } //如果没有异常,则用覆盖老的beanDefainition(concurrentHashMap的key相同则覆盖) this.beanDefinitionMap.put(beanName, beanDefinition); } else { //还没有注册,添加到缓存集合中 //已经开始创建 if (hasBeanCreationStarted()) { // Cannot modify startup-time collection elements anymore (for stable iteration) //给bean定义对象存储结合添加上锁,防止多线程操作 synchronized (this.beanDefinitionMap) { //将bean定义信息存到对象的concurrentHashMap集合中 this.beanDefinitionMap.put(beanName, beanDefinition); //Copy on Write 设计模式,既读写分离思想,先创建一个新的集合,然后把原来的集合放到新的里,老的集合不影响读取操作,然后再将老的集合的引用指向新的引用 List<String> updatedDefinitions = new ArrayList<String>(this.beanDefinitionNames.size() + 1); updatedDefinitions.addAll(this.beanDefinitionNames); updatedDefinitions.add(beanName); this.beanDefinitionNames = updatedDefinitions; if (this.manualSingletonNames.contains(beanName)) { //同样的设计思想:在java的concurrent并发包下有对应的集合设计 Set<String> updatedSingletons = new LinkedHashSet<String>(this.manualSingletonNames); updatedSingletons.remove(beanName); this.manualSingletonNames = updatedSingletons; } } } else { // Still in startup registration phase //仍旧在启动注册阶段 this.beanDefinitionMap.put(beanName, beanDefinition); this.beanDefinitionNames.add(beanName); this.manualSingletonNames.remove(beanName); } this.frozenBeanDefinitionNames = null; } if (oldBeanDefinition != null || containsSingleton(beanName)) { //如果已经存在,销毁当前bean相关的信息 resetBeanDefinition(beanName); } } //===============================================================非注解bean注册过程结束========================================================= //================================================================注解类bean的解析并创建Class对象过程开始==================================================== //BeanDefinitionParserDelegate的parseCustomElement方法 public BeanDefinition parseCustomElement(Element ele) { return parseCustomElement(ele, null); } //BeanDefinitionParserDelegate的重载方法parseCustomElement public BeanDefinition parseCustomElement(Element ele, BeanDefinition containingBd) { //根据命名空间回去对应命名空间的处理器:例如context命名空间的处理器为ContextNamespaceHandler String namespaceUri = getNamespaceURI(ele); NamespaceHandler handler = this.readerContext.getNamespaceHandlerResolver().resolve(namespaceUri); if (handler == null) { error("Unable to locate Spring NamespaceHandler for XML schema namespace [" + namespaceUri + "]", ele); return null; } //调用命名空间的处理器方法进行解析,返回bean定义信息 return handler.parse(ele, new ParserContext(this.readerContext, this, containingBd)); } //ContextNamespaceHandler的父类NamespaceHandlerSupport的parse方法 public class ContextNamespaceHandler extends NamespaceHandlerSupport { @Override public void init() { //注册各种bean定义解析器 registerBeanDefinitionParser("property-placeholder", new PropertyPlaceholderBeanDefinitionParser()); registerBeanDefinitionParser("property-override", new PropertyOverrideBeanDefinitionParser()); registerBeanDefinitionParser("annotation-config", new AnnotationConfigBeanDefinitionParser()); registerBeanDefinitionParser("component-scan", new ComponentScanBeanDefinitionParser()); registerBeanDefinitionParser("load-time-weaver", new LoadTimeWeaverBeanDefinitionParser()); registerBeanDefinitionParser("spring-configured", new SpringConfiguredBeanDefinitionParser()); registerBeanDefinitionParser("mbean-export", new MBeanExportBeanDefinitionParser()); registerBeanDefinitionParser("mbean-server", new MBeanServerBeanDefinitionParser()); }} //NamespaceHandlerSupport的parse方法 public BeanDefinition parse(Element element, ParserContext parserContext) { //根据空间下的标签获取解析器进行解析元素并返回bean定义信息:如component-scan获取到的为ComponentScanBeanDefinitionParser()解析器 return findParserForElement(element, parserContext).parse(element, parserContext); } //ComponentScanBeanDefinitionParser的parse方法 public BeanDefinition parse(Element element, ParserContext parserContext) { //获取扫描包信息配置新 String basePackage = element.getAttribute(BASE_PACKAGE_ATTRIBUTE); basePackage = parserContext.getReaderContext().getEnvironment().resolvePlaceholders(basePackage); String[] basePackages = StringUtils.tokenizeToStringArray(basePackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS); // Actually scan for bean definitions and register them. //根据应用上下文获取扫描器 ClassPathBeanDefinitionScanner scanner = configureScanner(parserContext, element); //扫描配置的包获取bean的定义信息 Set<BeanDefinitionHolder> beanDefinitions = scanner.doScan(basePackages); //注册所有bean定义信息 registerComponents(parserContext.getReaderContext(), beanDefinitions, element); return null; } //ClassPathBeanDefinitionScanner 类的doScan方法 protected Set<BeanDefinitionHolder> doScan(String... basePackages) { Assert.notEmpty(basePackages, "At least one base package must be specified"); Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<BeanDefinitionHolder>(); for (String basePackage : basePackages) { //扫描包获取bean定义新 Set<BeanDefinition> candidates = findCandidateComponents(basePackage); for (BeanDefinition candidate : candidates) { ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate); candidate.setScope(scopeMetadata.getScopeName()); String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry); if (candidate instanceof AbstractBeanDefinition) { postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName); } if (candidate instanceof AnnotatedBeanDefinition) { AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate); } if (checkCandidate(beanName, candidate)) { BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName); definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry); beanDefinitions.add(definitionHolder); //注册bean定义信息:registry==beanFactory ->DefaultListableBeanFactory //在XmlBeanDefinitionReader 的父类->AbstractBeanDefinitionReader构造中传入 registerBeanDefinition(definitionHolder, this.registry); } } } return beanDefinitions; }//================================================================注解类bean的解析并创建Class对象过程开始====================================================//================================================================注解类bean的注册过程参考非注解bean注册过程====================================================
阅读全文
0 0
- Spring源码-IOC(三)
- Spring源码阅读三 IOC
- spring源码学习之路---IOC实现原理(三)
- Spring Framework源码(三):IOC容器配置文件加载
- spring源码学习之路---IOC实现原理(三)
- spring源码学习之路---IOC实现原理(三)
- Spring源码阅读(三)—IOC容器依赖注入
- Spring源码-IOC(一)
- Spring源码-IOC(二)
- Spring学习笔记(三)- Spring IoC容器启动源码分析
- 浅析Spring IoC源码(三)分析refresh()方法前的准备篇(一)
- 小读spring ioc源码(三)——XmlWebApplicationContext初始化的整体过程
- 【Spring源码--IOC容器的实现】(三)BeanDefinition的载入和解析【I】
- 【Spring源码--IOC容器的实现】(三)BeanDefinition的载入和解析【II】
- spring源码学习之路---深度分析IOC容器初始化过程(三)
- Spring源码解析-BeanDefinition在IOC容器中的注册(三)
- 【Spring】Spring的IOC(控制反转)/DI(依赖注入)原理(三):Spring启动加载配置文件源码分析
- Spring源码学习(一)------ IoC
- android实现静默更新安装并自动启动
- sigsuspend()函数作用
- 朱啸虎不投60后被怼毫无教养,投资人拿钱砸人都如此狂妄自大吗?
- Android DialogFragment在屏幕旋转之后,输入框内的文字消失的原因
- python读取Kafka
- Spring源码-IOC(三)
- echarts 多个series图表的tooltip自定义
- 7-11 畅通工程之局部最小花费问题(最小生成树+并查集)
- python 利用utf-8编码判断中文英文字符
- sql 批量插入(一个数据库的表数据,添加到另一个数据库表) 数据类型nText和varchar在运算符equals不兼容的问题解决方案
- 一些sql语句的练习题及解答
- Linux根目录下重要目录的作用
- django 分页效果实现(djangorestframework内置以及django内置方法)
- 有趣有料的英语