Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 将ContextLoaderListener添加到ServletContext的目的是什么?_Java_Spring_Spring Mvc - Fatal编程技术网

Java 将ContextLoaderListener添加到ServletContext的目的是什么?

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

在阅读了几篇关于用纯Java替换xml配置的教程之后,
初始值设定项
类中有一条语句我不理解:

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
}