HttpServletBean 源码解析

577 阅读1分钟

HttpServletBean是spring mvc中的一个servlet基类,它直接继承HttpServlet类并重写了init()方法

了解servlet的伙伴都知道servlet的最重要的三个方法

  • servlet容器创建一个servlet对象的时候会调用其init()方法进行初始化
  • 通过service()方法处理请求,不管你是post还是get请求,最终还是由service()方法处理
  • 销毁的时候可以通过destroy()方法关闭文件流或者关闭数据库连接等操作

那么HttpServletBean重写了init()方法具体做了一些什么事嘞

  • 获取到servletconfig 中 init-param的spring mvc 配置,并且封装成PropertyValues对象
  • 将servlet类转换成BeanWrapper,让spring更好的操作javabean的属性
  • 自定义ResourceLoader编辑器
  • 调用initServletBean方法后面会被其子类FrameworkServlet去实现,FrameworkServlet初始化了webApplicationContext容器
@Override
public final void init() throws ServletException {

   // Set bean properties from init parameters.
   //解析init-param封装成PropertyValues对象
   PropertyValues pvs = new ServletConfigPropertyValues(getServletConfig(), this.requiredProperties);
   if (!pvs.isEmpty()) {
      try {
         /**
         *将servlet类转换成BeanWrapper,BeanWrapper是spring用来操作javabean的工具,使用BeanWrapper
         *可以直接对javabean属性赋值
         */
         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) {
         if (logger.isErrorEnabled()) {
            logger.error("Failed to set bean properties on servlet '" + getServletName() + "'", ex);
         }
         throw ex;
      }
   }

   // Let subclasses do whatever initialization they like.
   //空方法,交给子类去实现
   initServletBean();
}

//获取到ServletConfig中init-param,也就是web.xml中的init-param,加载到spring mvc的配置封装PropertyValue对象
//requiredProperties表示某些属性必须存在,用来验证配置
public ServletConfigPropertyValues(ServletConfig config, Set<String> requiredProperties)
      throws ServletException {

   Set<String> missingProps = (!CollectionUtils.isEmpty(requiredProperties) ?
         new HashSet<>(requiredProperties) : null);

   Enumeration<String> paramNames = config.getInitParameterNames();
   while (paramNames.hasMoreElements()) {
      String property = paramNames.nextElement();
      Object value = config.getInitParameter(property);
      addPropertyValue(new PropertyValue(property, value));
      if (missingProps != null) {
         missingProps.remove(property);
      }
   }

   // Fail if we are still missing properties.
   if (!CollectionUtils.isEmpty(missingProps)) {
      throw new ServletException(
            "Initialization from ServletConfig for servlet '" + config.getServletName() +
            "' failed; the following required properties were missing: " +
            StringUtils.collectionToDelimitedString(missingProps, ", "));
   }
}