编写和发布自己的自定义事件有许多步骤。按照在这一章给出的说明来编写,发布和处理自定义 spring 事件。
步骤 | 描述 |
---|---|
1 | 创建一个名称为 springexample 的项目,并且在创建项目的 src 文件夹中创建一个包 com.tutorialspoint。 |
2 | 使用 add external jars 选项,添加所需的 spring 库,解释见 spring hello world example 章节。 |
3 | 通过扩展 applicationevent,创建一个事件类 customevent。这个类必须定义一个默认的构造函数,它应该从 applicationevent 类中继承的构造函数。 |
4 | 一旦定义事件类,你可以从任何类中发布它,假定 eventclasspublisher 实现了 applicationeventpublisheraware。你还需要在 xml 配置文件中声明这个类作为一个 bean,之所以容器可以识别 bean 作为事件发布者,是因为它实现了 applicationeventpublisheraware 接口。 |
5 | 发布的事件可以在一个类中被处理,假定 eventclasshandler 实现了 applicationlistener 接口,而且实现了自定义事件的 onapplicationevent 方法。 |
6 | 在 src 文件夹中创建 bean 的配置文件 beans.xml 和 mainapp 类,它可以作为一个 spring 应用程序来运行。 |
7 | 最后一步是创建的所有 java 文件和 bean 配置文件的内容,并运行应用程序,解释如下所示。 |
这个是 customevent.java 文件的内容:
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.java 文件的内容:
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.java 文件的内容:
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.java 文件的内容:
package com.tutorialspoint;
import org.springframework.context.configurableapplicationcontext;
import org.springframework.context.support.classpathxmlapplicationcontext;
public class mainapp {
public static void main(string[] args) {
configurableapplicationcontext context =
new classpathxmlapplicationcontext("beans.xml");
customeventpublisher cvp =
(customeventpublisher) context.getbean("customeventpublisher");
cvp.publish();
cvp.publish();
}
}
下面是配置文件 beans.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.0.xsd">
<bean id="customeventhandler"
class="com.tutorialspoint.customeventhandler"/>
<bean id="customeventpublisher"
class="com.tutorialspoint.customeventpublisher"/>
</beans>
一旦你完成了创建源和 bean 的配置文件后,我们就可以运行该应用程序。如果你的应用程序一切都正常,将输出以下信息:
my custom event
my custom event