Spring事件监听Demo
Spring事件监听实现了观察者模式。本Demo在junit4测试环境中实现
主要有三个类事件类、类、事件发布类(⼊⼝)
事件类必须继承 ApplicationEvent,代码如下:
import org.junit.runner.RunWith;
import t.ApplicationEvent;
import st.context.ContextConfiguration;
import st.context.junit4.SpringJUnit4ClassRunner;
/**
* Created by *** on 2016/3/15.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "l")
public class StudentAddEventTest extends ApplicationEvent {
private String sname;
public StudentAddEventTest(Object source, String sname) {
super(source);
this.sname = sname;
}
public String getSname() {
return sname;
}
}
Listener类需实现 ApplicationListener 接⼝ ApplicationListener可以传⼊⼀个泛型的事件类型变量,也可以不传。不传的话,需要在监听到事件发⽣时(onApplicationEvent)⾃⼰判断该事件是不是⾃⼰要监听的事件。
import org.junit.runner.RunWith;
import t.ApplicationListener;
import org.springframework.stereotype.Component;
import st.context.ContextConfiguration;
import st.context.junit4.SpringJUnit4ClassRunner;
/**
* Created by *** on 2016/3/15.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "l")
@Component
public class StudentAddListenerTest implements ApplicationListener<StudentAddEventTest> {
@Override
public void onApplicationEvent(StudentAddEventTest studentAddEventTest) {
String sname = Sname();
System.out.println("增加的学⽣的名字为:::"+sname);
}
}
事件发布类实现了 ApplicationContextAware ,实现这个主要是为了拿到 ApplicationContext实例,进⽽调⽤他的 publishEvent⽅法。感觉不实现ApplicationContextAware应该也可以。。。
:
import org.junit.Test;
import org.junit.runner.RunWith;spring framework版本查看
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import t.ApplicationContext;
import t.ApplicationContextAware;
import org.springframework.stereotype.Component;
import st.context.ContextConfiguration;
import st.context.junit4.SpringJUnit4ClassRunner;
/**
* Created by *** on 2016/3/15.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "l")
@Component
public class StudentAddBeanTest implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
@Autowired
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public void addStudent(String sname){
StudentAddEventTest addEvent = new StudentAddEventTest(this, sname);
applicationContext.publishEvent(addEvent);
}
@Test
public void addTest(){
StudentAddBeanTest studentBean = new StudentAddBeanTest();
studentBean.addStudent("张三");
studentBean.addStudent("李四");
}
}
需要注意的是 StudentAddListenerTest ——Listener类,StudentAddBeanTest ——事件发布类需在spring容器中注册,Demo中在 l配置了
扫描<context:component-scan> </context:component-scan>路径
然后在类上加了注解@Component,运⾏测试⽅法addTest()经过测试,能顺利实现既定⽬标。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论