spring事件

spring的事件为bean与bean之间的通信提供了支持,当一个bean处理完一个任务后,希望另一个bean知道并做相应的处理,这时,我们就需要让另一个bean监听当前bean所发送的事件

  步骤:

    1:自定义事件,继承ApplicationEvent 实现方法

    2:定义事件监听器,实现ApplicationListener 实现方法

    3:使用容器发布类,比如:ApplicationContext的publishEvent方法

代码如下:

  自定义事件

public class DemoEvent extends ApplicationEvent{
private String msg;
public DemoEvent(Object source) {
super(source);
}
public DemoEvent(Object source, String msg) {
super(source);
this.msg = msg;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}

自定义事件监听器

@Component
public class DemoEventListener implements ApplicationListener<DemoEvent>{

public void onApplicationEvent(DemoEvent demoEvent) {
String msg=demoEvent.getMsg();
System.out.println("自定义事件bean被创建了:"+msg);
}
}

使用容器发布事件

@Component
public class DemoEventPublish {
@Autowired
private ApplicationContext context;
public void publish(String msg){
this.context.publishEvent(new DemoEvent(this, msg));
}
}

@Configuration
@ComponentScan
public class DemoEventConfig {

}

public class DemoEventMain {
public static void main(String[] args) {
AnnotationConfigApplicationContext context=
new AnnotationConfigApplicationContext(DemoEventConfig.class);
DemoEventPublish bean = context.getBean(DemoEventPublish.class);
bean.publish("hello applicationContext Event");
}
}

运行结果:

  自定义事件bean被创建了:hello applicationContext Event

 

转载于:https://www.cnblogs.com/zhangshaobin/p/6028546.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值