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

基于Spring代码的配置-IllegalArgumentException:ServletContext是必需的

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

基于Spring代码的配置-IllegalArgumentException:ServletContext是必需的

在您的情况下,这仅对于

ApplicationContext
传递给来说很重要
DispatcherServlet
。该
DispatcherServlet
构造函数指出

给定的Web应用程序上下文可能会或可能不会刷新。如果尚未刷新(推荐的方法),则会发生以下情况:

  • 如果给定上下文还没有父级,则将根应用程序上下文设置为父级。
  • 如果尚未为给定上下文分配一个ID,则会为其分配一个ID
  • ServletContext
    ServletConfig
    对象将被委托给应用程序上下文
  • postProcessWebApplicationContext
    将被称为
  • ApplicationContextInitializers
    通过“ contextInitializerClasses” init-
    param或setContextInitializers属性指定的任何内容都将应用。
  • refresh()
    如果上下文实现,将被调用
    ConfigurableApplicationContext

如果上下文已经刷新,则在用户已根据其特定需求执行(或未执行)这些操作的假设下,以上内容均不会发生。

因此,对于

DispatcherServlet
,您必须执行以下操作

AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();dispatcherContext.register(DispatcherConfig.class);// will take care of calling refresh() on the ApplicationContextServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));

这对于

DispatcherServlet
配置是必需的,因为由于
@EnableWebMvc
(或等效
<mvc:annotation-driven>
)而生成的某些bean 需要Servlet容器提供的
ServletContext
和/或
ServletConfig
对象。

根上下文不应具有此类依赖性,因此可以安全地执行此操作

AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();rootContext.register(AppConfig.class);rootContext.refresh();

请注意,您可以

AnnotationConfigWebApplicationContext
通过将
@Configuration
类作为参数传递给其构造函数来创建该对象。



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

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

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