ApplicationEvent 与 ApplicationListener 的使用 及 思考

  1. 我们先看怎么使用:

一 肯定是搭建好的 spring 工程。这里不搭建了。

这里有两个 Bean 继承 ApplicationEvent :

/**
 * Created by linving on 2016/12/9.
 */
public class TestBean2 extends ApplicationEvent {
    String source;

    public TestBean2(String source) {
        super(source);
        this.source = source;
    }

    @Override
    public String getSource() {
        return source;
    }

    public void setSource(String source) {
        this.source = source;
    }
}
/**
 * Created by linving on 2016/12/9.
 */
public class TestBean3 extends ApplicationEvent {
    String source;

    public TestBean3(String source) {
        super(source);
        this.source = source;
    }

    @Override
    public String getSource() {
        return source;
    }

    public void setSource(String source) {
        this.source = source;
    }
}

都分别 继承 ApplicationEvent ,ApplicationEvent 是一个 抽象类。

这里有个 Bean 继承 ApplicationListener:

只要继承这个 接口 并注入 spring 容器中 就能接收消息。

/**
 * Created by linving on 2016/12/9.
 */
@Component
public class AppEventListener implements ApplicationListener<TestBean2> {
    Logger logger = LoggerFactory.getLogger(AppEventListener.class);

    @Override
    public void onApplicationEvent(TestBean2 testBean2) {
        logger.error(" 收到消息 ..... " + testBean2.getSource());
    }
}

ApplicationListener 是一个接口 里面有 一个 方法 继承的时候重写:

    void onApplicationEvent(E var1);

最后看一下怎么使用:


/**
 * Created by linving on 2016/12/9.
 */
public class EventListenerTestCase extends BankTestCase {

    @Autowired
    ApplicationContext context;

    @Test
    public void pushMsg(){
        TestBean2 testBean2 = new TestBean2("2");
        context.publishEvent(testBean2);

        //在 AppEventListener 可以接受到消息
    }
}

通过 ApplicationContext 我们可以 post 一个 ApplicationEvent 。

最后 在ApplicationListener 里面可以得到 这个post 对象。
ApplicationListener 中 可以通过泛型 去过滤想要的 对象的类型。


例如上面post 的是  TestBean2  对象

ApplicationListener<TestBean2> 所以能接收到。

ApplicationListener<TestBean3>  的话就不行

这就很方便我们过滤信息。

ApplicationContext 负责 发送 ApplicationEvent 事件,而 ApplicationListener 负责接收 ApplicationEvent 事件,通过泛型过滤。有点像 观察者模式。

这样做的目的有很多
一个是很好的解耦。减少模块之间的依赖。
也可以做消息传播,广播等。去触发 某一个事件。

个人觉得 解耦 是最大的好处。可惜 现在项目中很少人 用这个功能 。太可惜了。

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值