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

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值