您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何使用基于纯Java的配置来配置Spring MVC?

如何使用基于纯Java的配置来配置Spring MVC?

你需要对进行以下更改,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.xmlServlet规范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("/");
  }
}
java 2022/1/1 18:20:28 有469人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶