我的任务是清理由已久的开发人员编写的一些旧代码。我设法整理了大部分内容,但是Web MVC初始化程序中有一些代码阻止了我的所有尝试。
public class SpringWebMvcInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
public void onStartup(ServletContext servletContext) {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
ServletRegistration.Dynamic dispatcherServlet = servletContext.addServlet("dispatcherServlet", new DispatcherServlet(context));
dispatcherServlet.addMapping("/foo/", "/bar");
dispatcherServlet.setAsyncSupported(true);
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding("utf-8");
FilterRegistration encodingFilterRegistration = servletContext.addFilter("characterEncodingFilter", characterEncodingFilter);
encodingFilterRegistration.
addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/");
}
protected Class<?>[] getRootConfigClasses() {
return new Class[]{};
}
protected Class<?>[] getServletConfigClasses() {
return new Class[] {SpringMvcConfig.class};
}
protected String[] getServletMappings() {
return new String[] {"/foo/", "/bar"};
}
}
理想情况下,我想做的是使用此onStartup()
方法调用super.onStartup()
,并让Spring框架通过@Beans
处理上下文,调度程序,过滤器等。 。但是,无论我尝试过什么,都无法在编译时或运行时失败。能做到吗?而且,如果是这样,怎么办?
这是配置类(如果相关):
@Configuration
@EnableWebMvc
public class SpringMvcConfig extends WebMvcConfigurerAdapter {
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
@Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("classpath:i18n/messages");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
}