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

<?xml version="1.0" encoding="utf-8"?>
<persons>
    <person id="100">
        <name >Tom</name>
        <age>20</age>
    </person>  
</persons>
b.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
	   xmlns:aop="http://www.springframework.org/schema/aop"
	   xmlns:context="http://www.springframework.org/schema/context"
	   xmlns:mvc="http://www.springframework.org/schema/mvc"
	   xmlns:tx="http://www.springframework.org/schema/tx"
	   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	   xmlns:test="http://com.luanbin.interceptor/schema/test"
	   xsi:schemaLocation="http://www.springframework.org/schema/aop 
		http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 
		http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-3.0.xsd 
		http://www.springframework.org/schema/mvc 
		http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd 
		http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
	<mvc:annotation-driven />
	<context:component-scan base-package="com.tan.*" />
	<bean class="com.tan.tool.HtmlExtractServiceImple" />
	<bean id="velocityConfig" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">  
        <property name="configLocation" value="/WEB-INF/velocity.properties"/>   
        <property name="resourceLoaderPath" value="/WEB-INF/velocity/"/>
        <property name="velocityProperties">    
         <props>    
             <prop  key="input.encoding">UTF-8</prop>    
             <prop  key="output.encoding">UTF-8</prop>      
          </props>
         </property>
    </bean>  
      
     <bean id="velocityViewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">  
        <property name="cache" value="false"/>  
        <property name="prefix" value=""/>  
        <property name="suffix" value=".vm"/>  
        <property name="contentType" value="text/html;charset=UTF-8" />
        <property name="order" value="1" />  
        <property name="requestContextAttribute" value="rc" />
    </bean>
    <mvc:resources mapping="/static/**" location="/WEB-INF/static/"/>
</beans>
  相比於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<String, String> 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<String, String> schemaMappings = new ConcurrentHashMap<String, String>();
						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<String, Object> 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<String, Object> handlerMappings = new ConcurrentHashMap<String, Object>();
						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<String> actualDependentBeans = new LinkedHashSet<String>(dependentBeans.length);
					for (String dependentBean : dependentBeans) {
						if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
							actualDependentBeans.add(dependentBean);
						}
					}
					if (!actualDependentBeans.isEmpty()) {
						throw new BeanCurrentlyInCreationException(beanName,
								"Bean with name '" + beanName + "' has been injected into other beans [" +
								StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
								"] in its raw version as part of a circular reference, but has eventually been " +
								"wrapped. This means that said other beans do not use the final version of the " +
								"bean. This is often the result of over-eager type matching - consider using " +
								"'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
					}
				}
			}
		}

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

		return exposedObject;
	}

  需要尤其注意的是代碼中的三個函數: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<PropertyValue> 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<PropertyValue> deepCopy = new ArrayList<PropertyValue>(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的注入功能進行分析


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章