Java 将ContextLoaderListener添加到ServletContext的目的是什么?
在阅读了几篇关于用纯Java替换xml配置的教程之后,Java 将ContextLoaderListener添加到ServletContext的目的是什么?,java,spring,spring-mvc,Java,Spring,Spring Mvc,在阅读了几篇关于用纯Java替换xml配置的教程之后,初始值设定项类中有一条语句我不理解: public class Initializer implements WebApplicationInitializer { @Override public void onStartup(ServletContext servletContext) throws ServletException { AnnotationConfigWebApplicationConte
初始值设定项
类中有一条语句我不理解:
public class Initializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext applicationContext;
applicationContext = new AnnotationConfigWebApplicationContext();
applicationContext.register(Config.class);
// What is the purpose of the following statement?
servletContext.addListener(new ContextLoaderListener(applicationContext));
ServletRegistration.Dynamic dispatcher;
dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(applicationContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
如果没有servletContext.addListener(…)
语句,我的应用程序似乎运行得很好
ServletContext
中的官方文档声明,我不骗你:
/**
* TODO SERVLET3 - Add comments
* @param <T> TODO
* @param t TODO
* @throws UnsupportedOperationException If [...]
* @since Servlet 3.0
*/
public <T extends EventListener> void addListener(T t);
…那么,将
ContextLoaderListener
添加到ServletContext
的目的到底是什么?一般来说,使用ContextLoaderListener
完全是可选的。它用于将ApplicationContext
和ServletContext
显式绑定在一起
现在,我将你的问题改为:
将ContextLoaderListener添加到JspCServletContext的目的是什么?
在您的情况下,正如您所注意到的,即使您为您的ServletContext
提供了ContextLoaderListener
,也不会使用它。因此,保持简单,并删除此处无用的ContextLoaderListener
@Override
public <T extends EventListener> void addListener(T t) {
// NOOP
}