spring的事件,为Bean与Bean之间通信提供了支持,当一个Bean处理完成之后,希望另一个Bean知道后做相应的事情,这时我们就让另外一个Bean监听当前Bean所发送的事件。
spring的事件应该遵循:
1.自定义事件,集成:ApplicationEvent
2.自定义事件监听,实现ApplicationListener
3.使用容器发布事件
//自定义事件
package ch2.event;
import org.springframework.context.ApplicationEvent;
//自定义事件
public class DemoEvent extends ApplicationEvent {
private static final long serialVerisionUID = 1L;
private String msg;
public DemoEvent(Object source, String msg) {
super(source);
// TODO Auto-generated constructor stub
this.msg = msg;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
//事件监听器
package ch2.event;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
//事件监听器
//@Component把普通pojo实例化到spring容器中,相当于配置文件中的<bean id="" class=""/>
//@service注入:当前类是spring管理的一个bean
@Component
public class DemoListener implements ApplicationListener<DemoEvent> {
@Override
public void onApplicationEvent(DemoEvent event) {
// TODO Auto-generated method stub
//接受消息
String msg = event.getMsg();
//打印消息
System.out.println("我(bean-DemoListener)接收到了bean-DemoPublisher发布的消息:"+msg);
}
}
//事件发送
package ch2.event;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
//事件发送
//把普通pojo实例化到spring容器中当成一个Bean
@Component
public class DemoPublisher {
//将ApplicationContext类的实体Bean注入到DemoPublisher中,让DemoPublisher拥有ApplicationContext的功能
//使用applicationContext来发布事件
@Autowired
ApplicationContext applicationContext;
public void publish(String msg)
{
//使用applicationContext的event来发布消息
applicationContext.publishEvent(new DemoEvent(this, msg));
}
}
配置类
package ch2.event;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ComponentScan;
//声明本类是一个配置类
@Configuration
//导入ch2.event包下的所有@Service,@Component,@Repository,@Controller注册为Bean
@ComponentScan("ch2.event")
public class EventConfig {
}
运行:
package ch2.event;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args)
{
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(EventConfig.class);
DemoPublisher demoPublisher = context.getBean(DemoPublisher.class);
demoPublisher.publish("hello application event");
context.close();
}
}
结果:
我(bean-DemoListener)接收到了bean-DemoPublisher发布的消息:hello application event