一.自定义事件
?
class="java" name="code">package com.zgw.event;
import org.springframework.context.ApplicationEvent;
public class EventDemo extends ApplicationEvent{
private static final long serialVersionUID = 1L;
private String msg;
public EventDemo(Object source,String msg) {
super(source);
this.msg=msg;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
?
二.事件监听器
?
package com.zgw.event; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; /** * 实现ApplicationListener接口,并指定事件类型EventDemo * @author zan * */ @Component public class ListenerDemo implements ApplicationListener<EventDemo> { //此方法是对消息进行处理 public void onApplicationEvent(EventDemo event) { String msg = event.getMsg(); System.out.println("我(bean-listenerDemo)接受到了bean-publisherDemo发布的消息:" + msg); } }
?三.事件发布类
?
package com.zgw.event;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
@Component
public class PublisherDemo {
//注入ApplicationContext用来发布事件
@Autowired
ApplicationContext applicationContext;
public void publish(String msg){
//调用publishEvent()来发布
applicationContext.publishEvent(new EventDemo(this, msg));
}
}
?
???? 四.配置类
?
package com.zgw.event; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan("com.zgw.event") public class EventConfig { }
?五.测试类
package com.zgw.event; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class TestEvent { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(EventConfig.class); PublisherDemo publisher = context.getBean(PublisherDemo.class); publisher.publish("Hello application event"); context.close(); } }
?运行结果如下:

?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?