2017-05-09 31 views
0

與純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 
} 

...那麼究竟什麼是增加的目的一個ContextLoaderListenerServletContext

回答

0

一般來說,使用ContextLoaderListener純粹是可選的。它用於綁定您的ApplicationContext和你一起ServletContext明確。現在

,我會改寫你的問題:

什麼是添加的ContextLoaderListener到JspCServletContext的目的是什麼?

在你的情況,因爲你已經注意到了,即使你提供一個ContextLoaderListenerServletContext,它不會被使用。因此,保持簡單,並在這裏刪除無用的ContextLoaderListener

相關問題