====================LogEvent类===============
package com.gc.action;
import
org.springframework.context.ApplicationEvent;
public class LogEvent extends
ApplicationEvent{
private
static final long serialVersionUID = 1L;
public
LogEvent(Object source) {
super(source);
}
}
==================LogListener类=================
package com.gc.action;
import java.text.SimpleDateFormat;
import java.util.Date;
import
org.springframework.context.ApplicationEvent;
import
org.springframework.context.ApplicationListener;
public class LogListener implements
ApplicationListener{
@Override
public
void onApplicationEvent(ApplicationEvent event) {
if(event
instanceof LogEvent){
SimpleDateFormat
format =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
format.setLenient(false);
String
currentDate = format.format(new Date());
System.out.println(currentDate
+"--------"+event.toString());
}
}
}
=======================Log类=======================
package com.gc.action;
import
org.springframework.beans.BeansException;
import
org.springframework.context.ApplicationContext;
import
org.springframework.context.ApplicationContextAware;
public class Log implements
ApplicationContextAware{
private
ApplicationContext applicationContext;
@Override
public
void setApplicationContext(ApplicationContext applicationContext) throws
BeansException {
this.applicationContext
=applicationContext;
}
public
int log(String log){
LogEvent
event =new LogEvent(log);
this.applicationContext.publishEvent(event);
return
0;
}
}
==================config.xml 配置文件=================
<?xml version="1.0"
encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC
"-//SPRING//DTD BEAN//EN"
"http://www./dtd/spring-beans.dtd">
<beans>
<!-- 负责国际化支持
-->
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<!--
国际化支持的定义在文件名为messages的文件中
-->
<property
name="basename">
<value>messages</value>
</property>
</bean>
<!-- 负责事件传递
-->
<bean id="log"
class="com.gc.action.Log"></bean>
<bean id="listener"
class="com.gc.action.LogListener"></bean>
</beans>
==========================TestLog 测试类==================
package com.gc.action;
import
org.springframework.context.ApplicationContext;
import
org.springframework.context.support.FileSystemXmlApplicationContext;
public class TestLog {
public
static void main(String[] args) {
ApplicationContext
actx =new FileSystemXmlApplicationContext("classpath:/config.xml");
Log
log =(Log) actx.getBean("log");
log.log("gf");
}
}
=============结果==============
2018-09-25
20:16:08--------com.gc.action.LogEvent[source=gf]
|