spring监听器的实现及实现原理,观察者模式,发布订阅的实现机制

6 篇文章 1 订阅

说到设计模式不得不提设计原则,可以说设计模式就是遵循着设计原则尔孕育而出的。
在这里插入图片描述

观察者模式

这里简单介绍一下观察者模式
在这里插入图片描述

import org.springframework.context.ApplicationContext;
import org.springframework.context.event.ApplicationContextEvent;
//自定义一个自己的事件原
public class MyEvent extends ApplicationContextEvent {

//自定义的事件原内部可以第一成员变量
    private String eventSource;


    public MyEvent(ApplicationContext source,String eventSource ) {
        super(source);
        this.eventSource = eventSource;
        System.out.println("MyEvent~~~~~~~~~~" + eventSource);
    }

    public String getEventSource() {
        return eventSource;
    }

    public void setEventSource(String eventSource) {
        this.eventSource = eventSource;
    }
}
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
//定义监听者01,监听MyEvent事件
@Component
public class SaveEvent implements ApplicationListener<MyEvent> {

    @Override
    public void onApplicationEvent(MyEvent myEvent) {
        System.out.println("SaveEvent事件监听到了MyEvent~~~~~~~"+myEvent.getEventSource());
    }
}
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
//定义监听者02,监听MyEvent事件
@Component
public class InsetEvent implements ApplicationListener<MyEvent> {

    @Override
    public void onApplicationEvent(MyEvent myEvent) {
        System.out.println("InsetEvent事件监听到了MyEvent~~~~~~~"+myEvent.getEventSource());
    }
}

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

@Component
public class EventTestService {

    @Autowired
    ApplicationContext applicationContext;

    public void eventTest(){
    	//这业务代码。。。。。。
        System.out.println("eventTest~~~~~~~~~");
		//驱动事件触发,创建我们自定义的事件对象
        applicationContext.publishEvent(new MyEvent(applicationContext,"eventTest执行"));
    }

}
  @Autowired
    private EventTestService eventTestService;

    @Test
    public void  testEvent(){
        eventTestService.eventTest();
    }

在这里插入图片描述
spring实现事件监听注意这里的事件处理,spring在这里其实就是简单的去寻找监听者并执行onApplicationEvent方法而已。
我们进入原码看看:applicationContext.publishEvent(new MyEvent(applicationContext,“eventTest执行”));

applicationContext.publishEvent();
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值