spring MVC的实现原理

1、典型配置

Spring MVC的一个典型配置如下:

<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:spring-context.xml</param-value>
</context-param>
<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
		<servlet-name>test</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath*:config/test-servlet.xml</param-value>
        </init-param>
		<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
		<servlet-name>test</servlet-name>
		<url-pattern>/</url-pattern>
</servlet-mapping>
从这个配置里面可以看到,一个是配置上下文的监听器,这个监听器负责整个ioc容器在web环境中的启动工作;另外一个就是配置spring MVC 的一个分发请求器。他们共同构成了spring和web容器的接口操作,他们与web容器的耦合是通过ServletContext来实现的。而ServletContext就为spring的IOC容器提供了一个宿主环境,这个宿主环境里面的ioc容器是通过.ContextLoader初始化的,而DispatcherServlet就负责web请求转发的建立,完成http的请求响应。

2、上下文的启动及初始化过程


在这个启动过程中看到系统加载是依赖web容器的servletContextListener来触发的,这个listener的触发会在如下时候:
当Servlet 容器启动或终止Web 应用时,会触发ServletContextEvent 事件,该事件由 ServletContextListener 来处理。在 ServletContextListener 接口中定义了处理ServletContextEvent 事件的两个方法。
1) contextInitialized(ServletContextEvent sce) :当Servlet 容器启动Web 应用时调用该方法。在调用完该方法之后,容器再对Filter 初始化,并且对那些在Web 应用启动时就需要被初始化的Servlet 进行初始化。
2)contextDestroyed(ServletContextEvent sce) :当Servlet 容器终止Web 应用时调用该方法。在调用该方法之前,容器会先销毁所有的Servlet 和Filter 过滤器。
所以spring会在web容器启动的时候借助这个监听器来创建它的上下文,而这个上下文的创建其实就是一个ico容器的初始化过程。而这个上下文初始化的过程同时也会把这个ServletContext给设置上,以供后面的WebApplicationContext来获取web容器级别的全局属性。
先看下这个创建的XmlWebApplicationContext上下文的类继承关系:

它的refresh过程其实是在AbstractApplicationContext完成的,如下代码:
public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			// Prepare this context for refreshing.
			prepareRefresh();

			// Tell the subclass to refresh the internal bean factory.
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

			// Prepare the bean factory for use in this context.
			prepareBeanFactory(beanFactory);

			try {
				// Allows post-processing of the bean factory in context subclasses.
				postProcessBeanFactory(beanFactory);

				// Invoke factory processors registered as beans in the context.
				invokeBeanFactoryPostProcessors(beanFactory);

				// Register bean processors that intercept bean creation.
				registerBeanPostProcessors(beanFactory);

				// Initialize message source for this context.
				initMessageSource();

				// Initialize event multicaster for this context.
				initApplicationEventMulticaster();

				// Initialize other special beans in specific context subclasses.
				onRefresh();

				// Check for listener beans and register them.
				registerListeners();

				// Instantiate all remaining (non-lazy-init) singletons.
				finishBeanFactoryInitialization(beanFactory);

				// Last step: publish corresponding event.
				finishRefresh();
			}

			catch (BeansException ex) {
				// Destroy already created singletons to avoid dangling resources.
				destroyBeans();

				// Reset 'active' flag.
				cancelRefresh(ex);

				// Propagate exception to caller.
				throw ex;
			}
		}
	}
这个就是之前spring ioc中已经讲到过的容器启动过程,在XmlWebApplicationContext它重写了beanDefinition的加载,如下代码:
@Override
	protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
		// Create a new XmlBeanDefinitionReader for the given BeanFactory.
		XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);

		// Configure the bean definition reader with this context's
		// resource loading environment.
		beanDefinitionReader.setEnvironment(this.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.
		initBeanDefinitionReader(beanDefinitionReader);
		loadBeanDefinitions(beanDefinitionReader);
	}
对于这个实现类它主要添加了对web环境和xml配置类的定义处理,例如:
/** Default config location for the root context */
	public static final String DEFAULT_CONFIG_LOCATION = "/WEB-INF/applicationContext.xml";


	/** Default prefix for building a config location for a namespace */
	public static final String DEFAULT_CONFIG_LOCATION_PREFIX = "/WEB-INF/";
这两个静态变量的定义就是专门为web环境来设置的,相对于配置资源的获取从以下这段重写的代码也可以看出来。
@Override
	protected String[] getDefaultConfigLocations() {
		if (getNamespace() != null) {
			return new String[] {DEFAULT_CONFIG_LOCATION_PREFIX + getNamespace() + DEFAULT_CONFIG_LOCATION_SUFFIX};
		}
		else {
			return new String[] {DEFAULT_CONFIG_LOCATION};
		}
	}
在上面时序图中有一个initWebApplicationContext的过程,这个过程里面有如下一段代码可以简单的说明一下:
if (this.context == null) {
				this.context = createWebApplicationContext(servletContext);
			}
也就是context的创建过程,这个createWebApplicationContext的实现如下:
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);
	}
在创建webApplicationXontext的时候这里面有一个选择上下文class的方法:
protected Class<?> determineContextClass(ServletContext servletContext) {
		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 {
			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容器的上下文全局属性里面有没有做设置,如果做了设置就使用这个类。如果没有设置就从一个默认的策略properties里面去获取这个配置。这个配置的默认文件内容如下:
# Default WebApplicationContext implementation class for ContextLoader.  
# Used as fallback when no explicit context implementation has been specified as context-param.  
# Not meant to be customized by application developers.  
  
org.springframework.web.context.WebApplicationContext=org.springframework.web.context.support.XmlWebApplicationContext  
也就是说spring的mvc默认上下文就是XmlWebApplicationContext ,验证了我们上面对这个类的分析。






  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值