监听spring加载完成后事件

时间:2022-03-09 14:59:09

有这个想法是在很早以前了,那时的我没有接触什么缓存技术,只知道hibernate有个二级缓存。没有用过memcache,也没有使用过redis。

只懂得将数据放到数组里或者集合里,一直不去销毁它(只有随着tomcat服务停止而销毁),用的时候从内存中读取就相当于缓存了,但是这么做有利也有弊。

好处:操作方便,随时取,随时存,只要方法封装好,代码也很清晰,易扩展。

弊端:因为只要一重启服务器,放在内存中的静态集合或静态数组肯定被回收了。导致一些重要的数据被干掉了。

话题扯远了,本文所讲的就是如何在spring 加载完毕后监听它的事件,并且保证只初始化一次。

配置其实很简单,如下:

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:jaxws="http://cxf.apache.org/jaxws"
xmlns:soap="http://cxf.apache.org/bindings/soap" xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xsi:schemaLocation="http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
http://cxf.apache.org/bindings/soap http://cxf.apache.org/schemas/configuration/soap.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd"> <!-- 初始化引擎使用 -->
<bean id="InitDataListener" class="cfs.wsdl.cache.InitDataListener">
<property name="dao">
<ref bean="commonBaseDaoHib" />
</property>
</bean> </beans>

spring配置文件

 package cfs.wsdl.cache;

 import java.util.Date;
import java.util.List;
import java.util.UUID; import org.springframework.beans.factory.InitializingBean; import com.google.gson.JsonObject;
import cfs.core.dao.CommonBaseDao; public class InitDataListener implements InitializingBean { private CommonBaseDao dao; public CommonBaseDao getDao() {
return dao;
} public void setDao(CommonBaseDao dao) {
this.dao = dao;
} @Override
public void afterPropertiesSet() throws Exception {
//将需要缓存的数据从数据库里缓存到内存中 //启动一个线程线程:
new Thread() {
public void run() {
while (true) {
try { //这里写一些需要定时执行的代码 //休眠30分钟,半个小时执行一次
Thread.sleep(60 * 1000*30);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
}.start(); } }

监听的事件类