Spring MVC 学习 -- 创建过程

时间:2023-03-08 16:23:40

Spring MVC 学习 -- 创建过程

Spring MVC我们使用的时候会在web.xml中配置

   <servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/spring-web.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

1.核心的类结构

Spring MVC 学习 -- 创建过程

  继承结构主要有五个类,GenericServlet和HttpServlet 是Java的,HttpServletBean、FrameworkServlet和DispatcherServlet是Spring MVC的。

    在图中还有三个接口:EnvironmentCapable、EnvironmentAware和ApplicationContextAware~

    XXXAware 在spring里标识对XXX可以感知 -- 白话的意思就是:某个类如果想要使用spring的一些东西,就可以通过实现XXXAware接口告诉spring,spring看到后会给你送过来,而接收的方式是通过实现接口唯一的setXXX

 public interface ApplicationContextAware extends Aware {

 void setApplicationContext(ApplicationContext applicationContext) throws BeansException;

 }

源码如上,使用的话写一个类实现ApplicationContextAware,然后实现setApplicationContext()方法就行,spring为自动调用这个方法将applicationContext传给我们。 

而EnvironmentCapable是为了实现getEnvironment去拿到ServletContext、ServletConfig、JndiProperty、系统环境变量和系统属性。

2.HttpServletBean

     public final void init() throws ServletException {
if (logger.isDebugEnabled()) {
logger.debug("Initializing servlet '" + getServletName() + "'");
} // Set bean properties from init parameters.
try {
PropertyValues pvs = new ServletConfigPropertyValues(getServletConfig(), this.requiredProperties);
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
ResourceLoader resourceLoader = new ServletContextResourceLoader(getServletContext());
bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, getEnvironment()));
initBeanWrapper(bw);
bw.setPropertyValues(pvs, true);
}
catch (BeansException ex) {
logger.error("Failed to set bean properties on servlet '" + getServletName() + "'", ex);
throw ex;
} // Let subclasses do whatever initialization they like.
initServletBean(); if (logger.isDebugEnabled()) {
logger.debug("Servlet '" + getServletName() + "' configured successfully");
}
}

主要看init()方法, 使用了BeanWrapper这个类对象,BeanWrapper是操作JavaBean的工具类,主要就是对属性进行操作。

3.FrameworkServlet

这个类是通过HttpServletBean中的initServletBean()方法进入的。

     protected final void initServletBean() throws ServletException {
getServletContext().log("Initializing Spring FrameworkServlet '" + getServletName() + "'");
if (this.logger.isInfoEnabled()) {
this.logger.info("FrameworkServlet '" + getServletName() + "': initialization started");
}
long startTime = System.currentTimeMillis(); try {
this.webApplicationContext = initWebApplicationContext();
initFrameworkServlet();
}
catch (ServletException ex) {
this.logger.error("Context initialization failed", ex);
throw ex;
}
catch (RuntimeException ex) {
this.logger.error("Context initialization failed", ex);
throw ex;
} if (this.logger.isInfoEnabled()) {
long elapsedTime = System.currentTimeMillis() - startTime;
this.logger.info("FrameworkServlet '" + getServletName() + "': initialization completed in " +
elapsedTime + " ms");
}
}

核心代码就try里面包含的两句,很显然主要用来初始化WebApplicationContext和初始化FrameworkServlet的。

     protected WebApplicationContext initWebApplicationContext() {
WebApplicationContext rootContext =
WebApplicationContextUtils.getWebApplicationContext(getServletContext());
WebApplicationContext wac = null; if (this.webApplicationContext != null) {
// A context instance was injected at construction time -> use it
wac = this.webApplicationContext;
if (wac instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac;
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 -> set
// the root application context (if any; may be null) as the parent
cwac.setParent(rootContext);
}
configureAndRefreshWebApplicationContext(cwac);
}
}
}
if (wac == null) {
// No context instance was injected at construction time -> see if one
// has been registered in the servlet context. If one exists, it is assumed
// that the parent context (if any) has already been set and that the
// user has performed any initialization such as setting the context id
wac = findWebApplicationContext();
}
if (wac == null) {
// No context instance is defined for this servlet -> create a local one
wac = createWebApplicationContext(rootContext);
} if (!this.refreshEventReceived) {
// Either the context is not a ConfigurableApplicationContext with refresh
// support or the context injected at construction time had already been
// refreshed -> trigger initial onRefresh manually here.
onRefresh(wac);
} if (this.publishContext) {
// Publish the context as a servlet context attribute.
String attrName = getServletContextAttributeName();
getServletContext().setAttribute(attrName, wac);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Published WebApplicationContext of servlet '" + getServletName() +
"' as ServletContext attribute with name [" + attrName + "]");
}
} return wac;
}

主要做了三件事:

  • 获取spring的根容器rootContext
  • 设置webApplicationContext并根据情况调用onRefresh方法
  • 将webApplicationContext设置到ServletContext中

4.DispatcherServlet

通过上面onRefresh()方法,调用initStrategies()方法,初始化策略组件。具体的内容就是用来初始化9个组件,每个组件的代码不一一贴出来了, 这几个方法都会去调用getDefaultStrategies()方法。

 protected <T> List<T> getDefaultStrategies(ApplicationContext context, Class<T> strategyInterface) {
String key = strategyInterface.getName();
String value = defaultStrategies.getProperty(key);
if (value != null) {
String[] classNames = StringUtils.commaDelimitedListToStringArray(value);
List<T> strategies = new ArrayList<T>(classNames.length);
for (String className : classNames) {
try {
Class<?> clazz = ClassUtils.forName(className, DispatcherServlet.class.getClassLoader());
Object strategy = createDefaultStrategy(context, clazz);
strategies.add((T) strategy);
}
catch (ClassNotFoundException ex) {
throw new BeanInitializationException(
"Could not find DispatcherServlet's default strategy class [" + className +
"] for interface [" + key + "]", ex);
}
catch (LinkageError err) {
throw new BeanInitializationException(
"Error loading DispatcherServlet's default strategy class [" + className +
"] for interface [" + key + "]: problem with class file or dependent class", err);
}
}
return strategies;
}
else {
return new LinkedList<T>();
}
}

5.代码测试

配置内容都不再贴了,启动Tomcat,然后去请求某个controller地址,进入HttpServletBean的init()方法

Spring MVC 学习 -- 创建过程

然后继续,因为WebApplicationContext是null,会进入

Spring MVC 学习 -- 创建过程

然后configureAndRefreshWebApplicationContext方法中会执行refresh(),这部分可以看spring bean加载过程和实例化。