栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

您需要对进行以下更改,

web.xml
以支持基于Java的配置。这将告诉您
DispatcherServlet
使用基于注释的Java配置加载配置
AnnotationConfigWebApplicationContext
。您只需要将Java配置文件的位置传递给
contextConfigLocation
param,如下所示

<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> </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("/");  }}

更新 :来自评论
官方Spring参考Spring 4
Release中也包含了一些更复杂的解释。

参考:

http://docs.spring.io/spring/docs/3.1.x/javadoc-
api/org/springframework/web/WebApplicationInitializer.html



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/514997.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号