Spring的ApplicationListener及Spring容器事件使用实例

来源:互联网 发布:阿里云备案承诺书下载 编辑:程序博客网 时间:2024/06/05 06:51

Event事件描述如下:
ContextRefreshedEvent 当ApplicationContext或者叫spring被初始化或者刷新initialized会触发该事件
ContextStartedEvent spring初始化完,时触发
ContextStoppedEvent spring停止后触发,一个停止了的动作,可以通过start()方法从新启动
ContextClosedEvent spring关闭,所有bean都被destroyed掉了,这个时候不能被刷新,或者从新启动了
RequestHandledEvent 请求经过DispatcherServlet时被触发,在request完成之后

这里对spring的两个事件触发后进行处理:
1、ContextRefreshedEvent
2、ContextClosedEvent

开发步骤:
1、先写好spring的配置文件:applicationContext.xml,引用到的是frameworkContext.xml文件

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xsi:schemaLocation="http://www.springframework.org/schema/beans                     http://www.springframework.org/schema/beans/spring-beans.xsd"> <import resource="classpath:frameworkContext.xml"/> </beans>

2、添加frameworkContext.xml文件,添加initProject这个bean,这样,在spring容器执行完之后的话,会执行initProject类中的onApplicationEvent()这个方法

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"       xmlns:mvc="http://www.springframework.org/schema/mvc"       xmlns:context="http://www.springframework.org/schema/context"       xmlns:aop="http://www.springframework.org/schema/aop"       xmlns:tx="http://www.springframework.org/schema/tx"       xmlns:jee="http://www.springframework.org/schema/jee"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xmlns:p="http://www.springframework.org/schema/p"       xmlns:c="http://www.springframework.org/schema/c"       xmlns:cache="http://www.springframework.org/schema/cache"       xsi:schemaLocation="http://www.springframework.org/schema/beans                           http://www.springframework.org/schema/beans/spring-beans.xsd                           http://www.springframework.org/schema/mvc                           http://www.springframework.org/schema/mvc/spring-mvc.xsd                           http://www.springframework.org/schema/context                           http://www.springframework.org/schema/context/spring-context.xsd                           http://www.springframework.org/schema/aop                           http://www.springframework.org/schema/aop/spring-aop.xsd                           http://www.springframework.org/schema/tx                           http://www.springframework.org/schema/tx/spring-tx.xsd                           http://www.springframework.org/schema/jee                           http://www.springframework.org/schema/jee/spring-jee.xsd                           http://www.springframework.org/schema/cache                             http://www.springframework.org/schema/cache/spring-cache.xsd ">  <!-- 加载数据库资源--> <context:property-placeholder location="file:${catalina.home}/test/conf/test_db.properties" />     <!-- Enable annotation driven controllers, validation etc... -->    <mvc:annotation-driven>        <mvc:message-converters>            <bean class="org.springframework.http.converter.StringHttpMessageConverter">                <property name="supportedMediaTypes">                    <list>                        <value>text/plain;charset=UTF-8</value>                        <value>text/html;charset=UTF-8</value>                    </list>                </property>            </bean>            <bean                class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">                <property name="supportedMediaTypes">                    <list>                        <value>application/json;charset=UTF-8</value>                    </list>                </property>                <property name="features">                    <array>                        <value>WriteMapNullValue</value>                        <value>WriteNullStringAsEmpty</value>                    </array>                </property>            </bean>        </mvc:message-converters>    </mvc:annotation-driven>    <!-- 静态资源配置 -->    <mvc:resources location="/static/" mapping="/static/**" cache-period="86400"/>    <!-- 自动装载com.test包下的bean -->    <context:component-scan base-package="com.test"/>    <!-- 数据源配置 -->    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">        <property name="driverClassName" value="${sqlDriver}" />        <property name="url"             value="${sqlUrl}" />        <property name="username"        value="${sqlUsername}" />        <property name="password"        value="${sqlPassword}" />        <property name="initialSize"     value="${sqlInitialSize}"/>  <!-- 连接池启动时创建的连接数 -->        <property name="maxTotal"        value="${sqlMaxTotal}"/>     <!-- 连接池最大连接数 -->        <property name="maxIdle"         value="${sqlMaxIdle}"/>      <!-- 连接池最大空闲连接数。推荐与 maxTotal 的值一致。 -->        <property name="maxWaitMillis"   value="${sqlMaxWaitMillis}"/><!-- 等待获取连接的时间.毫秒 -->    </bean><!-- 配置Spring对数据库事务的支持   -->    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" c:dataSource-ref="dataSource"/>    <!-- 开启注解事务的支持 -->    <tx:annotation-driven transaction-manager="txManager"/>    <!-- 配置Template -->    <bean id="qTemplate" class="org.springframework.jdbc.core.JdbcTemplate" c:dataSource-ref="dataSource"/>    <!-- 页面模板定义,使用JSP和JSTL -->    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>        <property name="prefix" value="/WEB-INF/jsp/"/>        <property name="suffix" value=".jsp"/>    </bean>    <!-- 支持上传文件 -->      <bean id="multipartResolver"        class="org.springframework.web.multipart.support.StandardServletMultipartResolver">    </bean>    <!-- 初始化类,当Spring容器启动完成后执行下面的这个Bean -->    <bean id="InitProject" class="com.test.framework.function.applifemanager.init.InitProject" destroy-method="close"/></beans>

3、编写initProject类,让它实现ApplicationListener监听者接口,并重写其onApplicationEvent(ApplicationEvent event) 方法:

public class InitProject implements ApplicationListener<ApplicationEvent> {    @Override    public void onApplicationEvent(ApplicationEvent event) {        if(event instanceof ContextRefreshedEvent){            ContextRefreshedEvent tempEvent=(ContextRefreshedEvent)event;            if(tempEvent.getApplicationContext().getParent() != null){//有父容器时执行如下init()方法                init(tempEvent.getApplicationContext());//spring被初始化或者刷新initialized会触发该事件            }        }else if(event instanceof ContextClosedEvent){            close();    //      spring容器关闭时调用这个自定义的close()方法,执行相关的操作,比如可以在spring容器关闭时关闭线程池         }    }       public void init(ApplicationContext applicationContext) {//      WebApplicationContext webApplicationContext =ContextLoader.getCurrentWebApplicationContext();         initBeanUtil(applicationContext);//初始化beanFactory,spring运行时要先初始化beanFactory        initSysConfig();//将数据库系统表相关参数数据加载到程序中,        initIPBlackList();//ip黑白名单        initUtils();//创建一些必要的文件夹        initCleanFile();//清除程序中的指定目录的临时文件夹及其文件    }/**     * 实例被销毁时调用     */    public void close(){         //关闭线程池    }}

(如有不正确,欢迎纠错)

阅读全文
0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 淘宝不支持花呗怎么办 淘宝误点了收货怎么办 注销公司社保户怎么办 手机媒体声音小怎么办 手机媒体没有声音怎么办 vivo开不了机怎么办 vivox5开不了机怎么办 淘宝商品出现问题怎么办 淘宝企业店新店怎么办 ps中的字体模糊怎么办 电商时代我们怎么办 电商虚假宣传怎么办 有货车找不到货源怎么办 天猫订单删除怎么办 微信支付不成功怎么办 滴滴订单未支付怎么办 在天猫买了假货怎么办 13岁有痛经怎么办 新店排名被降怎么办 淘宝店铺跳失率过大怎么办 国外打印很贵怎么办 店铺访客被拒怎么办 steam锁支付后怎么办 芦荟茎太长了怎么办 网店加盟被骗怎么办 分期乐忘记账号怎么办 贴墙纸遇到插头怎么办 用了屈臣氏过敏怎么办 商品房内电箱不符合标准怎么办 淘宝上恶意退货怎么办 退货率高了怎么办 淘宝店被关了钱怎么办 买家不申请退款怎么办 被买家恶意投诉怎么办 淘宝投诉后退款怎么办 天猫投诉不成功怎么办 苹果手机打不开流量怎么办 苹果6流量打不开怎么办 苹果笔记本电脑打不开软件怎么办 苹果软件蜂窝打不开怎么办 苹果手机wifi打不开怎么办