Spring ContextLoaderListener源码分析 .

扫码关注公众号:Java 技术驿站

发送:vip
将链接复制到本浏览器,永久解锁本站全部文章

【公众号:Java 技术驿站】 【加作者微信交流技术,拉技术群】

http://blog.csdn.net/hz_blog/article/details/7688921

当我们要自动装配ApplicationContext配置信息时候,首先在web.xml配置ContextLoaderListener,下面是部分源代码:

[java]
view plain
copy
print
?

  1. publicclass ContextLoaderListener implements ServletContextListener {
  2. private ContextLoader contextLoader;
  3. /**
  4. * Initialize the root web application context.
  5. */
  6. publicvoid contextInitialized(ServletContextEvent event) {
  7. this.contextLoader = createContextLoader();
  8. this.contextLoader.initWebApplicationContext(event.getServletContext());//注意此处
  9. }
  10. protected ContextLoader createContextLoader() {
  11. returnnew ContextLoader();
  12. }
  13. public ContextLoader getContextLoader() {
  14. returnthis.contextLoader;
  15. }
  16. publicvoid contextDestroyed(ServletContextEvent event) {
  17. if (this.contextLoader != null) {
  18. this.contextLoader.closeWebApplicationContext(event.getServletContext());
  19. }
  20. }
  21. }
    public class ContextLoaderListener implements ServletContextListener { private ContextLoader contextLoader; /** * Initialize the root web application context. */ public void contextInitialized(ServletContextEvent event) { this.contextLoader = createContextLoader(); this.contextLoader.initWebApplicationContext(event.getServletContext());//注意此处 } protected ContextLoader createContextLoader() { return new ContextLoader(); } public ContextLoader getContextLoader() { return this.contextLoader; } public void contextDestroyed(ServletContextEvent event) { if (this.contextLoader != null) { this.contextLoader.closeWebApplicationContext(event.getServletContext()); } } }

我们主要了解下WebApplicationContext是怎么初始化出来的,首先contextInitialized(ServletContextEvent event)方法的this.contextLoader.initWebApplicationContext(event.getServletContext());进去之后我们看到

[java]
view plain
copy
print
?

  1. public WebApplicationContext initWebApplicationContext(ServletContext servletContext)
  2. throws IllegalStateException, BeansException {
  3. if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) {
  4. thrownew IllegalStateException(
  5. “Cannot initialize context because there is already a root application context present – “ +
  6. “check whether you have multiple ContextLoader* definitions in your web.xml!”);
  7. }
  8. servletContext.log(“Initializing Spring root WebApplicationContext”);
  9. if (logger.isInfoEnabled()) {
  10. logger.info(“Root WebApplicationContext: initialization started”);
  11. }
  12. long startTime = System.currentTimeMillis();
  13. try {
  14. // Determine parent for root web application context, if any.
  15. ApplicationContext parent = loadParentContext(servletContext);
  16. // Store context in local instance variable, to guarantee that
  17. // it is available on ServletContext shutdown.
  18. this.context = createWebApplicationContext(servletContext, parent);
  19. servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);//注意此处
  20. currentContextPerThread.put(Thread.currentThread().getContextClassLoader(), this.context);
  21. if (logger.isDebugEnabled()) {
  22. logger.debug(“Published root WebApplicationContext as ServletContext attribute with name [“ +
  23. WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + “]”);
  24. }
  25. if (logger.isInfoEnabled()) {
  26. long elapsedTime = System.currentTimeMillis() – startTime;
  27. logger.info(“Root WebApplicationContext: initialization completed in “ + elapsedTime + ” ms”);
  28. }
  29. returnthis.context;
  30. }
  31. catch (RuntimeException ex) {
  32. logger.error(“Context initialization failed”, ex);
  33. servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
  34. throw ex;
  35. }
  36. catch (Error err) {
  37. logger.error(“Context initialization failed”, err);
  38. servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err);
  39. throw err;
  40. }
  41. }
     public WebApplicationContext initWebApplicationContext(ServletContext servletContext) throws IllegalStateException, BeansException { if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) { throw new IllegalStateException( "Cannot initialize context because there is already a root application context present - " + "check whether you have multiple ContextLoader* definitions in your web.xml!"); } servletContext.log("Initializing Spring root WebApplicationContext"); if (logger.isInfoEnabled()) { logger.info("Root WebApplicationContext: initialization started"); } long startTime = System.currentTimeMillis(); try { // Determine parent for root web application context, if any. ApplicationContext parent = loadParentContext(servletContext); // Store context in local instance variable, to guarantee that // it is available on ServletContext shutdown. this.context = createWebApplicationContext(servletContext, parent); servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);//注意此处 currentContextPerThread.put(Thread.currentThread().getContextClassLoader(), this.context); if (logger.isDebugEnabled()) { logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" + WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]"); } if (logger.isInfoEnabled()) { long elapsedTime = System.currentTimeMillis() - startTime; logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms"); } return this.context; } catch (RuntimeException ex) { logger.error("Context initialization failed", ex); servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex); throw ex; } catch (Error err) { logger.error("Context initialization failed", err); servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err); throw err; } }

注意此处部分,说明当我们要得到一个WebApplicationContext只需要在ServletContext中获取属性名为WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE的常量值就可以得到一个ApplicationContext,最终可以获取spring配置文件中任意一个Bean对象

eg:

[java]
view plain
copy
print
?

  1. public String execute() throws Exception {
  2. // TODO Auto-generated method stub
  3. ApplicationContext conn=(ApplicationContext)ServletActionContext.getServletContext().getAttribute(WebApplicationContext.class.getName() + “.ROOT”);
  4. System.out.println(conn.getBean(“biz”));
  5. return SUCCESS;
  6. }
     public String execute() throws Exception { // TODO Auto-generated method stub ApplicationContext conn=(ApplicationContext)ServletActionContext.getServletContext().getAttribute(WebApplicationContext.class.getName() + ".ROOT"); System.out.println(conn.getBean("biz")); return SUCCESS; }

或者直接使用org.springframework.web.context.support.WebApplicationContextUtils这个抽象的工具类来获得WebApplicationContext,该类的方法

[java]
view plain
copy
print
?

  1. publicstatic WebApplicationContext getWebApplicationContext(ServletContext sc) {
  2. return getWebApplicationContext(sc, WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
  3. }

来源:http://ddrv.cn

赞(0) 打赏
版权归原创作者所有,任何形式的转载请联系博主:daming_90:Java 技术驿站 » Spring ContextLoaderListener源码分析 .

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏