基于注解的SpringMVC自定义DispatcherServlet配置

时间:2023-01-05 06:46:18

通过重载AbstractAnnotationConfigDispatcherServletInitializer实现类的customizeRegistration()方法来自定义DispatcherServlet配置

在AbstractAnnotationConfigDispatcherServletInitializer将DispatcherServlet注册到Servlet容器之后,就会调用customizeRegistration()方法,并将Servlet注册后得到的ServletRegistration.Dynamic传递进来,通过重载customizeRegistration()方法,我们可以对DispatcherServlet进行额外的配置。

 public class SpringWebAppInit extends AbstractAnnotationConfigDispatcherServletInitializer {
//Spring容器
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{RootConfig.class};
} //SpringMVC容器
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{WebConfig.class};
} //DispatcherServlet映射关系
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
} @Override
protected void customizeRegistration(ServletRegistration.Dynamic registration) {
super.customizeRegistration(registration);
registration.setMultipartConfig(new MultipartConfigElement("/tmp/coreqi/uploads"));//配置对multipart的支持
registration.setLoadOnStartup(1);//设置load-on-startup优先级
}
}