第十八章 Spring中定制事件(Spring Framework3.1教程)

发布自己的事件有许多步骤要编写。按照本章给的说明去编写、发布并处理Spring定制事件。

步骤 

描述

1

创建一个SpringExample的项目并在src目录下创建com.tutorialspoint包。所有的类都在这个包下。

2

在Add External JARs选项卡中添加Spring库如在Spring Hello World章节中所讲。

3

创建一个事件类,定制类通过扩展ApplicationEvent。这个类必须定义一个默认的构造函数且继承ApplicationEvent类的构造函数。

4

一旦你定义了事件类,你可以从任何类中发布,我们说的事件发布类实现了ApplicationEventPublisherAware接口。你同样需要在XML配置文件中声明这个类,这样容器可以确定这个类是一个事件发布者因为它继承了ApplicationEventPublisherAware接口。

5

一个发布的事件可以在类中处理,我们说的事件处理类实现了ApplicationListener接口并且实现了onApplicationEvent方法对这个定制的事件。

6

在src目录下创建一个bean配置文件Beans.xml和MainApp类,作为一个Spring应用。

7

最后一步在Java类中和Bean配置文件中添加内容,并运行应用。

如下是CustomEvent类源代码:

package com.tutorialspoint;

import org.springframework.context.ApplicationEvent;

public class CustomEvent extends ApplicationEvent {

    public CustomEvent(Object source) {
        super(source);
    }

    public String toString() {
        return "My Custom Event";
    }
}

如下是CustomEventPublisher类源代码:

package com.tutorialspoint;

import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;

public class CustomEventPublisher implements ApplicationEventPublisherAware {

    private ApplicationEventPublisher publisher;

    public void setApplicationEventPublisher(ApplicationEventPublisher publisher) {
        this.publisher = publisher;
    }

    public void publish() {
        CustomEvent ce = new CustomEvent(this);
        publisher.publishEvent(ce);
    }
}

如下是CustomEventHandler类源代码:

package com.tutorialspoint;

import org.springframework.context.ApplicationListener;

public class CustomEventHandler implements ApplicationListener<CustomEvent> {

    public void onApplicationEvent(CustomEvent event) {
        System.out.println(event.toString());
    }

}

如下是MainApp类源代码:

package com.tutorialspoint;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp18 {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("Beans18.xml");

        CustomEventPublisher cvp = (CustomEventPublisher) context.getBean("customEventPublisher");

        cvp.publish();
        cvp.publish();
    }
}

一旦你完成了源代码和配置文件的创建,运行这个应用。如果应用一切正常,将会打印如下消息:

My Custom Event
My Custom Event








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值