1 回答
TA贡献1813条经验 获得超2个赞
如果我理解它,您想摆脱所有XML配置。
然后首先你必须实现WebApplicationInitializer哪个替换web.xml配置文件。你可以这样做:
public class CustomWebAppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(RootConfig.class);
ContextLoaderListener contextLoaderListener = new ContextLoaderListener(rootContext);
servletContext.addListener(contextLoaderListener);
AnnotationConfigWebApplicationContext webContext = new AnnotationConfigWebApplicationContext();
webContext.register(MvcConfig.class);
DispatcherServlet dispatcherServlet = new DispatcherServlet(webContext);
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", dispatcherServlet);
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
另一个步骤是为替换app-ctx.xml 的根上下文实现 Spring 配置:
@Configuration
@EnableWebMvc
@ComponentScan({"com.mzk.mavenproject1.service", "com.mzk.mavenproject1.model"})
public class RootConfig {
// ... provide another custom beans when needed
}
最后一步是为 MVC 实现配置,替换dispatcher-servlet.xml:
@Configuration
@EnableWebMvc
@ComponentScan("com.mzk.mavenproject1.controller")
public class MvcConfig extends WebMvcConfigurerAdapter {
@Bean
ViewResolver internalViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
// ... provide another custom beans when needed
}
关于您关于课程数量的问题 - 是的,您只能通过两个课程来完成:CustomWebAppInitializer并且MvcConfig所有内容都只有一个上下文。
CustomWebAppInitializer.onStartup() 方法体将如下所示:
AnnotationConfigWebApplicationContext webContext = new AnnotationConfigWebApplicationContext();
webContext.register(MvcConfig.class);
ContextLoaderListener contextLoaderListener = new ContextLoaderListener(webContext);
servletContext.addListener(contextLoaderListener);
DispatcherServlet dispatcherServlet = new DispatcherServlet(webContext);
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", dispatcherServlet);
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
添加回答
举报