你需要对进行以下更改,web.xml
以支持基于Java的配置。这将告诉你DispatcherServlet
使用基于注释的Java配置加载配置AnnotationConfigWebApplicationContext
。你只需要将Java配置文件的位置传递给contextConfigLocationparam
,如下所示
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/*path to your WebSpringConfig*/ </param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
更新:在不更改web.xml的情况下进行相同操作
你甚至可以在没有web.xml
Servlet规范3.0 web.xml
可选的情况下执行此操作。你只需要实现/配置WebApplicationInitializer
接口来配置ServletContext
,它将允许你以DispatcherServlet
编程方式创建,配置和执行注册。好处是可以WebApplicationInitializer
自动检测到。
总而言之,一个需要实现的WebApplicationInitializer
摆脱方法web.xml
。
public class MyWebAppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext container) {
// Create the 'root' Spring application context
AnnotationConfigWebApplicationContext rootContext =
new AnnotationConfigWebApplicationContext();
rootContext.register(WebSpringConfig.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(DispatcherConfig.class);
// Register and map the dispatcher servlet
ServletRegistration.Dynamic dispatcher =
container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}