使用spring 事件非常简单
首先继承 ApplicationEvent
public class SampleEvent extends ApplicationEvent {
private String otherProperty;
public String getOtherProperty() {
return otherProperty;
}
public void setOtherProperty(String otherProperty) {
this.otherProperty = otherProperty;
}
public SampleEvent(Object source) {
super(source); //To change body of overridden methods use File | Settings | File Templates.
}
}
然后做 SampleEventListener 实现 ApplicationListener
public class SampleEventListener implements ApplicationListener {
protected Log log = LogFactory.getLog(this.getClass());
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof SampleEvent) {
SampleEvent se = (SampleEvent) event;
System.out.println(se.getOtherProperty());
log.debug(se.getOtherProperty());
}
}
}
然后实现 SampleEventPublisher 发布 事件
public class SampleEventPublisher implements ApplicationContextAware {
private ApplicationContext ctx;
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.ctx = applicationContext;
}
public void publishAction(String otherProperty) {
SampleEvent se = new SampleEvent(this);
se.setOtherProperty(otherProperty);
ctx.publishEvent(se);
}
}
applicationContext 配置
<beans></beans>
<bean class="com.test.spring.applicationEvent.SampleEventListener"></bean>
<bean class="com.test.spring.applicationEvent.SampleEventPublisher" id="samplePublisher"></bean>
做 Test 测试
public class SampleEventTest extends TestCase {
protected void setUp() throws Exception {
super.setUp(); //To change body of overridden methods use File | Settings | File Templates.
}
public void testSampleEventPublish() {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
SampleEventPublisher sep = (SampleEventPublisher) ctx.getBean("samplePublisher");
sep.publishAction("this is sample property");
}
}