在您的情况下,这仅对于
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类作为参数传递给其构造函数来创建该对象。



