1 回答

TA貢獻1813條經(jīng)驗 獲得超2個贊
如果我理解它,您想擺脫所有XML配置。
然后首先你必須實現(xiàn)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 的根上下文實現(xiàn) Spring 配置:
@Configuration
@EnableWebMvc
@ComponentScan({"com.mzk.mavenproject1.service", "com.mzk.mavenproject1.model"})
public class RootConfig {
// ... provide another custom beans when needed
}
最后一步是為 MVC 實現(xiàn)配置,替換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
}
關于您關于課程數(shù)量的問題 - 是的,您只能通過兩個課程來完成:CustomWebAppInitializer并且MvcConfig所有內(nèi)容都只有一個上下文。
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("/");
添加回答
舉報