SpringMVC源码分析--整体结构

整体结构如图:

    

一、解析aware和capable

1. XXXAware 在Spring里表示对XXX可以感知,通俗点解释就是,如果某个类里面想要使用spring的一些东西,就可以通过实现XXXAware接口告诉spring,spring看到后就给你送过来,而接受的方式就是通过实现接口唯一的方法setXXX。

例如:有一个类想要使用ApplicationContext接口,然后实现ApplicationContextAware接口,并set,spring就会把applicationContext传给我们。

2. XXXCapable,表示有什么的能力,这里的EnvironmentCapable唯一的方法是getEnvironment,当spring需要的时候,直接提供给spring

二、Environment

    在HttpServletBean中的Environment使用的是StandardServletEnvironment,这里封装了ServletContext,ServletConfig,JndiProperty,系统环境变量和系统属性。可以通过一个Controller类实现implements EnvironmentWare接口(记得set这个接口),debug调试查看:如下

@Controller
public class HelloController implements EnvironmentAware {

    private final Log logger = LogFactory.getLog(HelloController.class);
    private  Environment environment;

    @RequestMapping("/")
    public String Head(){
        return "index.html";
    }

    @RequestMapping(value = "/index.action",method = RequestMethod.GET)
    public String index(Model model){
        logger.info("====正在运行index页面====");    //设置断点
        model.addAttribute("msg","欢迎使用Springmvc");
        return "go.jsp";
    }
    @Override
    public void setEnvironment(Environment environment) {
        this.environment=environment;
    }
}

    debug后,查看environment的值,在propertySources可以看到有

     1> ServerCofigPropertySource      -包含StandardWrapperFacade,封装的是ServletConfig,web.xml定义的contextConfigLocation可以在config下看到,还有相关的参数

       2> ServerContextPropertySource    --保存的是ServletContext

        3>JndiPropertySource                    --保存的是Jndi

       4> MapPropertySource                    --存放的是我们使用的虚拟机属性,如java的版本,操作系统,用户主目录,临时目录,Catalina的目录等内容

        5>SystemEnvironmentPropertySource    --存放的是环境变量,比如我们设置的JAVA_HOME,Path等属性

三、HttpServletBean类

        它的init方法

      public final void init() throws ServletException {
        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Initializing servlet '" + this.getServletName() + "'");
        }

        try {//获取到设置的参数
            PropertyValues pvs = new HttpServletBean.ServletConfigPropertyValues(this.getServletConfig(), this.requiredProperties);
            BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this); //bw表示DispatcherServlet
            ResourceLoader resourceLoader = new ServletContextResourceLoader(this.getServletContext());
            bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, this.getEnvironment()));
            this.initBeanWrapper(bw);            
            bw.setPropertyValues(pvs, true);    //将初始的配置设置到DispatcherServlet中
        } catch (BeansException var4) {
            this.logger.error("Failed to set bean properties on servlet '" + this.getServletName() + "'", var4);
            throw var4;
        }

        this.initServletBean();            //模板方法,子类初始化的入口方法
        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Servlet '" + this.getServletName() + "' configured successfully");
        }

    }

    BeanWrapper使用方式:

            这个类是Spring提供的一个用来操作JavaBean属性的工具,使用它可以直接修改一个对象的属性。例如新建的User实体类,

        User user = new User()            
        BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(user)
        bw.setPropertyValue("userName",“visonws”);
        System.out.println(user.getUserName()) ; //输出visonws

四、FramewordServlet类

        这个类基层HttpServletBean,所以他的入口方法是initServletBean方法,代码如下;

    protected final void initServletBean() throws ServletException {
        this.getServletContext().log("Initializing Spring FrameworkServlet '" + this.getServletName() + "'");
        if (this.logger.isInfoEnabled()) {
            this.logger.info("FrameworkServlet '" + this.getServletName() + "': initialization started");
        }

        long startTime = System.currentTimeMillis();

        try {//主要的方法是这两个
            this.webApplicationContext = this.initWebApplicationContext();
            this.initFrameworkServlet();
        } catch (ServletException var5) {
            this.logger.error("Context initialization failed", var5);
            throw var5;
        } catch (RuntimeException var6) {
            this.logger.error("Context initialization failed", var6);
            throw var6;
        }

        if (this.logger.isInfoEnabled()) {
            long elapsedTime = System.currentTimeMillis() - startTime;
            this.logger.info("FrameworkServlet '" + this.getServletName() + "': initialization completed in " + elapsedTime + " ms");
        }

    }
          1.  核心代码是this.webApplicationContext = this.initWebApplicationContext();和

                                this.initFrameworkServlet();

            1> initFramwordServlet方法是模板,子类可以覆盖做一些初始化方法

            2> initWebApplicationContext方法源代码如下:

    protected WebApplicationContext initWebApplicationContext() {
        //这里获取rootContext
        WebApplicationContext rootContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        WebApplicationContext wac = null;
        //构造方法设置了webApplicationContext
        if (this.webApplicationContext != null) {
            wac = this.webApplicationContext;
            if (wac instanceof ConfigurableWebApplicationContext) {
                ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext)wac;
                if (!cwac.isActive()) {
                    if (cwac.getParent() == null) {
                        cwac.setParent(rootContext);
                    }

                    this.configureAndRefreshWebApplicationContext(cwac);
                }
            }
        }
        //当webApplicationContext已经存在ServletContext中时,通过配置在Servlet中的ContextAttribue获取
        if (wac == null) {
            wac = this.findWebApplicationContext();
        }
        如果webApplicationContext还没有创建,则创建一个
        if (wac == null) {
            wac = this.createWebApplicationContext(rootContext);
        }
        当ContextRefreshEvent事件没有触发时调用此方法,模板方法,可以在子类重写
        if (!this.refreshEventReceived) {
            this.onRefresh(wac);
        }

        if (this.publishContext) {
            String attrName = this.getServletContextAttributeName();
            this.getServletContext().setAttribute(attrName, wac);
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("Published WebApplicationContext of servlet '" + this.getServletName() + "' as ServletContext attribute with name [" + attrName + "]");
            }
        }

        return wac;
    }

        1.2 intiWebApplicationContext方法主要做了三件事:

            1>:获取spring的根容器rootContext.

            2>:设置webApplicationContext并根据情况调用onRefresh方法

            3>:将webApplicationContext设置到ServletContext中

    五、DispatchServlet 类

            他的创建过程主要是对九大组件的初始化。

        在FrameworkServlet类中initWebApplicationContext调用了onRefresh   方法,Dispatcher类继承FrameworkServlet类,在DispatcherServlet类中的onRefresh方法中调用了    this.initStrategies(context);这个方法代码如下:

   protected void onRefresh(ApplicationContext context) {
        this.initStrategies(context);
   }
   protected void initStrategies(ApplicationContext context) {
        this.initMultipartResolver(context);    //这个没有默认实现方法
        this.initLocaleResolver(context);
        this.initThemeResolver(context);
        this.initHandlerMappings(context);
        this.initHandlerAdapters(context);
        this.initHandlerExceptionResolvers(context);
        this.initRequestToViewNameTranslator(context);
        this.initViewResolvers(context);
        this.initFlashMapManager(context);
    }

        从上面的初始化策略可以看到,这里初始化了九个组件,通过初始化方法层层查询,例如:initLocaleResoler(context),这里的context是WebApplicationContext,代码:

private void initLocaleResolver(ApplicationContext context) {
        try {
            this.localeResolver = (LocaleResolver)context.getBean("localeResolver", LocaleResolver.class);
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("Using LocaleResolver [" + this.localeResolver + "]");
            }
        } catch (NoSuchBeanDefinitionException var3) {
            this.localeResolver = (LocaleResolver)this.getDefaultStrategy(context, LocaleResolver.class);
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("Unable to locate LocaleResolver with name 'localeResolver': using default [" + this.localeResolver + "]");
            }
        }

    }

    先通过localeResolver从容器里面找,如果没有找到,则采用默认的localResolver.,方法是getDefaultStrategy,通过层层查询,最后调用的是在DispatcherServlet同一个目录下的一个DispatchServlet.properties文件,如下所示:

# Default implementation classes for DispatcherServlet's strategy interfaces.
# Used as fallback when no matching beans are found in the DispatcherServlet context.
# Not meant to be customized by application developers.//这里是定制开发,不可对外更改的

org.springframework.web.servlet.LocaleResolver=org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver

org.springframework.web.servlet.ThemeResolver=org.springframework.web.servlet.theme.FixedThemeResolver
//红色标记的有多个默认配置类Handler开头的
org.springframework.web.servlet.HandlerMapping=org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,\
	org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping

org.springframework.web.servlet.HandlerAdapter=org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,\
	org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,\
	org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter

org.springframework.web.servlet.HandlerExceptionResolver=org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver,\
	org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver,\
	org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver

org.springframework.web.servlet.RequestToViewNameTranslator=org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator
//这个也可以有多个,这里默认只配置了一个而已
org.springframework.web.servlet.ViewResolver=org.springframework.web.servlet.view.InternalResourceViewResolver

org.springframework.web.servlet.FlashMapManager=org.springframework.web.servlet.support.SessionFlashMapManager
    这里定义了八个默认组件,不包含MultipartResolver文件上传组件。有些还配置了多个,注意的是,这里的默认配置并不是最优配置,只是在没有配置的时候,可以有一个默认值

总结:HttpServletBean直接继承HttpServlet,作用是将Servlet的配置的设置到相应的属性,FrameworkServlet初始化WebApplicationContext,DispatcherServlet初始化自身的9个组件。

    


猜你喜欢

转载自blog.csdn.net/weixin_40792878/article/details/80991706