您的位置:首页 > 移动开发

ApplicationEvent 与 ApplicationListener 的使用 及 思考

2016-12-09 15:43 295 查看
我们先看怎么使用:

一 肯定是搭建好的 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 事件,通过泛型过滤。有点像 观察者模式。

这样做的目的有很多

一个是很好的解耦。减少模块之间的依赖。

也可以做消息传播,广播等。去触发 某一个事件。

个人觉得 解耦 是最大的好处。可惜 现在项目中很少人 用这个功能 。太可惜了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring 继承 bean