Spring事件编程源码案例
Spring框架广泛应用了事件,并开发了事件机制。此事件机制的目的是为了在内部使用,如监听上下文被刷新等,监听者的APi接口是org.springframework.context.ApplicationListener,方法是onApplicationEvent
如一个实现监听的代码:
package com.yohanliyanage.blog.springevents;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
public class MyEventListener implements ApplicationListener {
private static final Log LOG = LogFactory.getLog(MyEventListener.class);
public void onApplicationEvent(ApplicationEvent event) {
LOG.info("Event Occurred : " + event);
}
}
使用 @Component或XML配置都可
下面是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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- Adding the listener class to Spring Container automatically registers it for events -->
<bean class="com.yohanliyanage.blog.springevents.MyEventListener" />
</beans>
客户端调用代码:
public class Main {
public static void main(String[] args) throws InterruptedException {
ApplicationContext context =
new ClassPathXmlApplicationContext("classpath:META-INF/spring/application-context.xml");
}
}
输出结果:
18:45:00 INFO Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@7a982589: startup date [Sun Sep 30 18:45:00 IST 2012]; root of context hierarchy
18:45:00 INFO Loading XML bean definitions from class path resource [META-INF/spring/application-context.xml]
18:45:00 INFO Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@33e228bc: defining beans [com.yohanliyanage.blog.springevents.MyEventListener#0]; root of factory hierarchy
18:45:00 INFO Event Occurred : org.springframework.context.event.ContextRefreshedEvent[source=org.springframework.context.support.ClassPathXmlApplicationContext@7a982589: startup date [Sun Sep 30 18:45:00 IST 2012]; root of context hierarchy]