用于Servlet 3.0的MultipartResolver的Spring 4 Java Config


问题内容

我正在采用全Java的方法来配置Spring
MVC,无法弄清楚如何以编程方式将其MultipartConfigElement与我的关联DispatcherServlet

Spring文档指出:

为了使用基于Servlet 3.0的多部分解析,您需要在web.xml中用“ multipart-config”部分或
在编程性Servlet注册 中用 javax.servlet.MultipartConfigElement
标记DispatcherServlet

http://docs.spring.io/spring/docs/4.0.4.RELEASE/spring-framework-
reference/htmlsingle/#mvc-
multipart

这是我的WebApplicationInitializer代码:

public class DispatcherServletInitializer implements WebApplicationInitializer {

    private static final Logger logger = LoggerFactory.getLogger(DispatcherServletInitializer.class);

    @Override
    public void onStartup(ServletContext container) {

        // Create the 'root' Spring application context
        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.register(AppConfig.class);

        // Manage the lifecycle of the root application context
        container.addListener(new ContextLoaderListener(rootContext));

        // Create the dispatcher servlet's Spring application context
        AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
        dispatcherContext.register(WebConfig.class);

        //HOW CAN I ASSOCIATE THIS CONFIG WITH MY DISPATCHER SERVLET?
        MultipartConfigElement config = new MultipartConfigElement("C:\\Temp", 20848820, 418018841, 1048576);
        DispatcherServlet dispatcherServlet = new DispatcherServlet(dispatcherContext);

        // Register and map the dispatcher servlet
        ServletRegistration.Dynamic dispatcher = 
            container.addServlet("dispatcher", dispatcherServlet);
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/*");
    }

}

如何将关联到MultipartConfigElement我的DispatcherServlet?我没有看到任何类似setMultipartConfiguration的方法或任何接受它的构造函数。

另请注意,我的WebConfig声明了MultipartResolver

@Bean
public StandardServletMultipartResolver multipartResolver(){
    return new StandardServletMultipartResolver();
}

但是Spring文档指出:

Configuration settings such as maximum sizes or storage locations need to be applied at that Servlet registration level as Servlet 3.0 does not allow for those settings to be done from the MultipartResolver.

任何指导将不胜感激。


问题答案:

看来您需要这个:

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));