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

如何使用基于纯Java的配置来配置Spring MVC?,第1张

如何使用基于纯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> </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("/");  }}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5110125.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-17
下一篇 2022-11-17

发表评论

登录后才能评论

评论列表(0条)

保存