将ContextLoaderListener添加到ServletContext的目的是什么?
问题描述:
与纯Java替代xml配置读取多个教程之后,在Initializer
类中的一个声明,我不明白:将ContextLoaderListener添加到ServletContext的目的是什么?
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);
而且里面JspCServletContext
的实施实际上是空的:
@Override
public <T extends EventListener> void addListener(T t) {
// NOOP
}
...那么究竟什么是增加的目的一个ContextLoaderListener
到ServletContext
?
答
一般来说,使用ContextLoaderListener
纯粹是可选的。它用于绑定您的ApplicationContext
和你一起ServletContext
明确。现在
,我会改写你的问题:
什么是添加的ContextLoaderListener到JspCServletContext的目的是什么?
在你的情况,因为你已经注意到了,即使你提供一个ContextLoaderListener
您ServletContext
,它不会被使用。因此,保持简单,并在这里删除无用的ContextLoaderListener
。