zoukankan      html  css  js  c++  java
  • java web程序启动加载 ContextLoaderListener

    浅析ContextLoaderListener

    大家可能对下面这段代码再熟悉不过了

      <context-param> 
        <param-name>contextConfigLocation</param-name>  
        <param-value>classpath:applicationContext.xml</param-value> 
      </context-param>  
      <listener> 
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
      </listener> 

    没错,这就是在web应用加载完之前先加载ContextLoaderListener,然后通过这个类里面的某个方法去加载spring配置文件

    下面我们新建一个自己的ContextLoaderListene

    新建立一个java类型,继承ContextLoaderListener,然后实现他的两个主要的方法contextInitialized,contextDestroyed;在contextInitialized,contextDestroyed这两个方法里面你就可以做自己想做的事情了,然后再web.xml里面添加一个listener,将自己的class加进去即可

    java代码如下:

     1 package com.software.aaa;
     2 
     3 import javax.servlet.ServletContextEvent;
     4 
     5 import org.springframework.web.context.ContextLoaderListener;
     6 
     7 public class Test extends ContextLoaderListener{
     8 
     9     @Override
    10     public void contextInitialized(ServletContextEvent event) {
    11         // TODO Auto-generated method stub
    12         System.out.println("contextInitialized.............");
    13     }
    14     
    15     @Override
    16     public void contextDestroyed(ServletContextEvent event) {
    17         // TODO Auto-generated method stub
    18         System.out.println("contextDestroyed.............");
    19     }
    20 }

    web.xml代码如下

    1   <listener>
    2       <listener-class>com.software.aaa.Test</listener-class>
    3   </listener>

    在写的过程中我发现一个问题:contextDestroyed这个方法怎么都不会被调用,后来不小心重新启动项目,却意外的调用了此方法,甚是不解!!!

  • 相关阅读:
    NABCD
    返回一个整数数组中最大子数组的和。
    四则运算
    返回一个二维整数数组中最大子数组的和
    返回一个整数数组中最大子数组的和
    解决方案
    测绘软件
    ImageMagick还是GraphicsMagick?
    opencv-2.4.11编译备忘
    Graphicmagick编译
  • 原文地址:https://www.cnblogs.com/gavinYang/p/3498481.html
Copyright © 2011-2022 走看看