发布自己的事件有许多步骤要编写。按照本章给的说明去编写、发布并处理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