Spring 4 Java Config for MultipartResolver for Servlet 3.0

后端 未结 2 622
抹茶落季
抹茶落季 2021-02-08 15:52

I\'m taking an all-Java approach to Spring MVC configuration and cannot figure out how to associate a MultipartConfigElement with my DispatcherServlet

相关标签:
2条回答
  • 2021-02-08 16:22

    Looks like you need this:

    ServletRegistration.Dynamic dispatcher = 
                container.addServlet("dispatcher", dispatcherServlet);
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("/*");
    
    dispatcher.setMultipartConfig(new MultipartConfigElement("/tmp", 1024*1024*5, 1024*1024*5*5, 1024*1024));
    
    0 讨论(0)
  • 2021-02-08 16:24

    Here is the solution compatible with AbstractAnnotationConfigDispatcherServletInitializer way of configuring the servlet. This is a bit less invasive than WebApplicationInitializer.

    It uses an override of AbstractAnnotationConfigDispatcherServletInitializer.customizeRegistration.

    public class MySpringWebSetup extends AbstractAnnotationConfigDispatcherServletInitializer
    {
      // Your usual obligatory configuration overrides:
      @Override protected Class<?>[] getRootConfigClasses() { ... }
      @Override protected Class<?>[] getServletConfigClasses() { ... }
      @Override protected String[] getServletMappings() { ... }
    
      // Optional configuration:
      @Override
      protected void customizeRegistration(Dynamic registration) {
        registration.setMultipartConfig(
          // Maybe use more sophisticated configuration than this:
          new MultipartConfigElement("")
        );
      }
    }
    

    I found it catching the stack trace of getServletMappings and thus getting into the code of org\springframework\web\servlet\support\AbstractDispatcherServletInitializer.java:

    protected void registerDispatcherServlet(ServletContext servletContext) {
    
        [more registration stuff was here]
    
        registration.setLoadOnStartup(1);
        registration.addMapping(getServletMappings());
        registration.setAsyncSupported(isAsyncSupported());
    
        Filter[] filters = getServletFilters();
        if (!ObjectUtils.isEmpty(filters)) {
            for (Filter filter : filters) {
                registerServletFilter(servletContext, filter);
            }
        }
    
    
        customizeRegistration(registration);
    }
    
    0 讨论(0)
提交回复
热议问题