Spring IOC 自定义事件
来源:互联网 发布:为什么淘宝退款打不开 编辑:程序博客网 时间:2024/05/02 06:46
在spring中我们可以自定义事件,并且可以使用ApplicationContext类型对象(就是spring容器container)来发布这个事件,事件发布之后,所有的ApplicaitonListener(监听器)实例都会被触发并调用指定方法onApplicationEvent()来处理.
例如:
例如:
自定义事件类RainEvent:
//spring容器中的自定义事件public class RainEvent extends ApplicationEvent {public RainEvent(Object source) {super(source);}}监听器类RainListener1:
public class RainListener1 implements ApplicationListener {public void onApplicationEvent(ApplicationEvent event) {if (event instanceof RainEvent) {System.out.println("唐僧大喊:" + event.getSource() + "赶快收衣服喽!");}}}监听器类RainListener2:
public class RainListener2 implements ApplicationListener {public void onApplicationEvent(ApplicationEvent event) {if (event instanceof RainEvent) {System.out.println("我们:" + event.getSource() + "太好了不用上课了!");}}}上面的instanceof用法我已经在这篇:Java instanceof关键字的详解 说过,不懂得可以去看下~
配置文件event.xml:
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd"> <!-- 只需要把这俩个监听器类交给spring容器管理就可以了 --><bean class="com.x.spring.test3.event.RainListener1"></bean><bean class="com.x.spring.test3.event.RainListener2"></bean></beans>测试类:
public class EventTest {public static void main(String[] args) {// TODO Auto-generated method stub//自定义事件try {String path = "com/x/spring/test3/event/event.xml";ApplicationContext container = new ClassPathXmlApplicationContext(path);/*spring容器发布事件之后,容器中的所有监听器都会调用指定方法去处理*//*所以我们需要提前把监听器对象配置spring容器里面*/container.publishEvent(new RainEvent("下雨了"));} catch (Exception e) {e.printStackTrace();}}}运行效果:
0 0
- Spring IOC 自定义事件
- Spring的IOC的事件的使用
- spring自定义事件监听
- Spring-自定义事件发布
- Spring自定义事件
- Spring中的自定义事件
- 【Java.Spring.Core】【IoC】自定义bean nature
- 自定义实现spring式的IOC
- Spring AOP与IOC以及自定义注解
- Spring IOC 自定义属性编辑器PropertyEditor
- spring 实现自定义 ioc(简单版)
- Spring IOC源码分析-自定义标签加载
- 第七章 Spring自定义事件
- Spring学习九:自定义事件
- 如何自定义事件(Spring事件机制浅谈)
- spring事件(三)--自定义事件
- IOC、Spring的IOC
- 自定义标签中 如何使用 Spring 的 ioc
- Java变量、数据类型。
- KMP算法
- MaterialDialog 仿Android 5.0原生的AlertDialog样式的对话框
- 宝剑锋从磨砺出
- 用Java继承来解决反射难以获取到的实例的思想
- Spring IOC 自定义事件
- 实现请求url或者restful webservice的方式
- AndroidStudio下SVN的解除
- python编辑器
- 12款经典图片轮播jquery插件
- Android开发——程序锁的实现(可用于开发钓鱼登录界面)
- JSP概述
- 1-Computer Networks and the Internet
- windos下没有dirent,导致纯c应用非常得不爽,本文介绍一个在windows下使用dirent的方法