SpringMvc学习心得(一)浅谈spring

本人在使用springmvc框架过程中产生了一点心得和体会,在此记录下来作为参考,如有疏漏敬请指正(所有与spring有关的jar包版本均为3.1.1.RELEASE)。

1.springmvc是什么?

  我认为springmvc是spring+mvc(这句话有点像废话)。换句话说,如果我们把搭建一个web项目认为是盖一座商场的话,spring是材料供应商,主要负责生产钢筋水泥等一些建筑材料。而mvc就像一个施工队,他规定了web项目的大致结构。不过此时的商场还只是一个毛坯房,还不能够使用。而springmvc的使用者就是装修队,他将毛坯房(mvc框架)转化为精美的店铺(业务逻辑),最终供消费者使用。

  综上所述,我认为在整个项目中最重要部分是spring而不是mvc。坦白的说,单从mvc的角度上来看,springmvc并不能算得上出色。但spring的IOC机制对项目的构建有着很大的帮助,这也是springmvc这么流行的原因之一。

2.关于spring的一些讨论

2.1:xsd文件的加载

  一提到spring,首先想到的一般就是IOC和AOP(面试经常被问到)。spring创建JavaBean的主要包含三个步骤:(1)解析xml文件;(2)构建beandefinition;(3)根据beandefinition反射JavaBean。

  spring解析xml文件使用的是dom方式进行解析,即整个xml文档都被加载进内存当中。spring本身不提供xml解析功能,该功能由第三方jar包提供。 

仔细比较下面两个xml文件:

a.xml



    
        Tom
        20
      
b.xml



	
	
	
	  
           
        
            
             
             UTF-8    
             UTF-8      
          
         
      
      
       
          
          
          
        
          
        
    
    
  相比于a.xml,b.xml多了好多内容,主要增加的是一些xsd文件的配置工作,比较这两个文件的目的是为了说明:相比于直接使用sun的api解析xml文件,spring干预了xml文件解析的过程,其主要工作是在解析xml文件之前手动加载自定义的xsd文件。spring通过自定义entityresolver的方式实现自定义xsd文件的加载工作。下面贴出具体代码:

XmlBeanDefinitionReader

protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
			throws BeanDefinitionStoreException {
		try {
			int validationMode = getValidationModeForResource(resource);
			Document doc = this.documentLoader.loadDocument(
					inputSource, getEntityResolver(), this.errorHandler, validationMode, isNamespaceAware());
			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);
		}
	}
  该函数的调用了getEntityResolver()方法,该方法返回的是ResourceEntityResolver实例。该实例的resolveEntity(String publicId, String systemId)会被调用,而该方法则调用其父类的PluggableSchemaResolver的同名方法。该同名方法中调用了getSchemaMapping()方法,其中schemaMappingsLocation在该类的构造函数中被赋值为“META-INF/spring.schemas”:

private Map getSchemaMappings() {
		if (this.schemaMappings == null) {
			synchronized (this) {
				if (this.schemaMappings == null) {
					if (logger.isDebugEnabled()) {
						logger.debug("Loading schema mappings from [" + this.schemaMappingsLocation + "]");
					}
					try {
						Properties mappings =
								PropertiesLoaderUtils.loadAllProperties(this.schemaMappingsLocation, this.classLoader);
						if (logger.isDebugEnabled()) {
							logger.debug("Loaded schema mappings: " + mappings);
						}
						Map schemaMappings = new ConcurrentHashMap();
						CollectionUtils.mergePropertiesIntoMap(mappings, schemaMappings);
						this.schemaMappings = schemaMappings;
					}
					catch (IOException ex) {
						throw new IllegalStateException(
								"Unable to load schema mappings from location [" + this.schemaMappingsLocation + "]", ex);
					}
				}
			}
		}
		return this.schemaMappings;
	}

  其中尤其需要注意PropertiesLoaderUtils.loadAllProperties方法,该方法能够扫描并加载包括web项目和引用jar包在内的所有具有相同路径的同名文件。(上面那句话说的比较拗口,举个简单的例子。如果web项目引用了两个jar包,这两个jar包的source folder中都有一个META-INF文件夹,而且该文件夹中都有一个叫做spring.schemas的文件。那么PropertiesLoaderUtils在调用loadAllProperties方法时会把这两个文件都进行加载。)。而spring.schemas存放的就是url和xsd文件路径的意义映射关系,spring获取了这一映射关系并加载了该文件,最后通过文件流的方式返回给XMLEntityManager供其在解析xml文件时使用。至此,校验xml文件需要的xsd文件就被成功加载了。

2.2:JavaBean的构建

  成功解析xml文件只是spring运行的第一步,接下来spring将xml解析出来的element转化为beandefinition。beandefinition规定了JavaBean的组成结构。spring依旧使用PropertiesLoaderUtils进行加载,不过这一次加载的是META-INF/spring.handler。通过该文件中的信息,spring获得并注册了xml元素与元素解析器之间的映射关系。

解析META-INF/spring.handler并注册映射关系的代码:

private Map getHandlerMappings() {
		if (this.handlerMappings == null) {
			synchronized (this) {
				if (this.handlerMappings == null) {
					try {
						Properties mappings =
								PropertiesLoaderUtils.loadAllProperties(this.handlerMappingsLocation, this.classLoader);
						if (logger.isDebugEnabled()) {
							logger.debug("Loaded NamespaceHandler mappings: " + mappings);
						}
						Map handlerMappings = new ConcurrentHashMap();
						CollectionUtils.mergePropertiesIntoMap(mappings, handlerMappings);
						this.handlerMappings = handlerMappings;
					}
					catch (IOException ex) {
						throw new IllegalStateException(
								"Unable to load NamespaceHandler mappings from location [" + this.handlerMappingsLocation + "]", ex);
					}
				}
			}
		}
		return this.handlerMappings;
	}
获取namespacehandler并解析成beandefinition的代码:

public BeanDefinition parseCustomElement(Element ele, BeanDefinition containingBd) {
		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;
		}
		return handler.parse(ele, new ParserContext(this.readerContext, this, containingBd));
	}
  namespacehandler只是一个句柄,他拥有元素名、解析器以及二者之间的一一映射关系。他将具体的解析过程交给解析器去完成
 获取解析器并解析element的代码:

public BeanDefinition parse(Element element, ParserContext parserContext) {
		return findParserForElement(element, parserContext).parse(element, parserContext);
	}
  根据element寻找解析器的代码:

private BeanDefinitionParser findParserForElement(Element element, ParserContext parserContext) {
		String localName = parserContext.getDelegate().getLocalName(element);
		BeanDefinitionParser parser = this.parsers.get(localName);
		if (parser == null) {
			parserContext.getReaderContext().fatal(
					"Cannot locate BeanDefinitionParser for element [" + localName + "]", element);
		}
		return parser;
	}

  BeanDefinitionParser的主要作用是创建一个BeanDefinition实例,该实例中是对JavaBean的描述,例如bean中的每个基本类型的值,bean中如果包含其他的bean,则将其他JavaBean的BeanDefinition也被注册到该JavaBean的BeanDefinition中。

  spring对JavaBean的实例化:spring根据beandefinition的定义,通过反射机制产生java对象,并为其配置响应的属性(property)

  spring对JavaBean实例化的代码:

protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) {
		// Instantiate the bean.
		BeanWrapper instanceWrapper = null;
		if (mbd.isSingleton()) {
			instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
		}
		if (instanceWrapper == null) {
			instanceWrapper = createBeanInstance(beanName, mbd, args);
		}
		final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
		Class beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);

		// Allow post-processors to modify the merged bean definition.
		synchronized (mbd.postProcessingLock) {
			if (!mbd.postProcessed) {
				applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
				mbd.postProcessed = true;
			}
		}

		// Eagerly cache singletons to be able to resolve circular references
		// even when triggered by lifecycle interfaces like BeanFactoryAware.
		boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
				isSingletonCurrentlyInCreation(beanName));
		if (earlySingletonExposure) {
			if (logger.isDebugEnabled()) {
				logger.debug("Eagerly caching bean '" + beanName +
						"' to allow for resolving potential circular references");
			}
			addSingletonFactory(beanName, new ObjectFactory() {
				public Object getObject() throws BeansException {
					return getEarlyBeanReference(beanName, mbd, bean);
				}
			});
		}

		// Initialize the bean instance.
		Object exposedObject = bean;
		try {
			populateBean(beanName, mbd, instanceWrapper);
			if (exposedObject != null) {
				exposedObject = initializeBean(beanName, exposedObject, mbd);
			}
		}
		catch (Throwable ex) {
			if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
				throw (BeanCreationException) ex;
			}
			else {
				throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
			}
		}

		if (earlySingletonExposure) {
			Object earlySingletonReference = getSingleton(beanName, false);
			if (earlySingletonReference != null) {
				if (exposedObject == bean) {
					exposedObject = earlySingletonReference;
				}
				else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
					String[] dependentBeans = getDependentBeans(beanName);
					Set actualDependentBeans = new LinkedHashSet(dependentBeans.length);
					for (String dependentBean : dependentBeans) {
						if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
							actualDependentBeans.add(dependentBean);
						}
					}
					if (!actualDependentBeans.isEmpty()) {
						throw new BeanCurrentlyInCreationException(beanName,
								"Bean with name '" + beanName + "' has been injected into other beans [" +
								StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
								"] in its raw version as part of a circular reference, but has eventually been " +
								"wrapped. This means that said other beans do not use the final version of the " +
								"bean. This is often the result of over-eager type matching - consider using " +
								"'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
					}
				}
			}
		}

		// Register bean as disposable.
		try {
			registerDisposableBeanIfNecessary(beanName, bean, mbd);
		}
		catch (BeanDefinitionValidationException ex) {
			throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
		}

		return exposedObject;
	}

  需要尤其注意的是代码中的三个函数:createBeanInstance,addSingletonFactory以及populateBean。其中 createBeanInstance从beandefinition当中获取对象的构造函数,并使用spring的工具类BeanUtils完成java对象的实例化工作。

  addSingletonFactory则将反射出来的JavaBean注册到beanfactory中,具体代码如下:

protected void addSingletonFactory(String beanName, ObjectFactory singletonFactory) {
		Assert.notNull(singletonFactory, "Singleton factory must not be null");
		synchronized (this.singletonObjects) {
			if (!this.singletonObjects.containsKey(beanName)) {
				this.singletonFactories.put(beanName, singletonFactory);
				this.earlySingletonObjects.remove(beanName);
				this.registeredSingletons.add(beanName);
			}
		}
	}
  populateBean通过setter方法对已经实例化的java对象进行进一步的处理,其核心功能由同一个类下面的函数applyPropertyValues完成

protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
		if (pvs == null || pvs.isEmpty()) {
			return;
		}

		MutablePropertyValues mpvs = null;
		List original;
		
		if (System.getSecurityManager()!= null) {
			if (bw instanceof BeanWrapperImpl) {
				((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext());
			}
		}

		if (pvs instanceof MutablePropertyValues) {
			mpvs = (MutablePropertyValues) pvs;
			if (mpvs.isConverted()) {
				// Shortcut: use the pre-converted values as-is.
				try {
					bw.setPropertyValues(mpvs);
					return;
				}
				catch (BeansException ex) {
					throw new BeanCreationException(
							mbd.getResourceDescription(), beanName, "Error setting property values", ex);
				}
			}
			original = mpvs.getPropertyValueList();
		}
		else {
			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 = pv.getName();
				Object originalValue = pv.getValue();
				Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
				Object convertedValue = resolvedValue;
				boolean convertible = bw.isWritableProperty(propertyName) &&
						!PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
				if (convertible) {
					convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter);
				}
				// Possibly store converted value in merged bean definition,
				// in order to avoid re-conversion for every created bean instance.
				if (resolvedValue == 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();
		}

		// Set our (possibly massaged) deep copy.
		try {
			bw.setPropertyValues(new MutablePropertyValues(deepCopy));
		}
		catch (BeansException ex) {
			throw new BeanCreationException(
					mbd.getResourceDescription(), beanName, "Error setting property values", ex);
		}
	}

至此,spring完成了解析xml文件以及实例化java对象的全部过程。之后的博客将对spring的注入功能进行分析


你可能感兴趣的:(Spring)