Spring ─ Custom EventsThere are number of steps to be taken to write and publish your own custom events. Follow the instructions given in this chapter to write, publish and handle Custom Spring Events.
package com.jtc;
import org.springframework.context.ApplicationEvent; public class CustomEvent extends ApplicationEvent{ public CustomEvent(Object source) { super(source); } public String toString(){ return "My Custom Event"; } } Following is the content of the CustomEventPublisher.java file
package com.jtc;
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); } } Following is the content of the CustomEventHandler.java file
package com.jtc;
import org.springframework.context.ApplicationListener; public class CustomEventHandler implements ApplicationListener<CustomEvent>{ public void onApplicationEvent(CustomEvent event) { System.out.println(event.toString()); } } Following is the content of the MainApp.java file
package com.jtc;
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(); } } Following is the configuration file 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.jtc.CustomEventHandler"/> <bean id="customEventPublisher" class="com.jtc.CustomEventPublisher"/> </beans> Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message:
y Custom Event
y Custom Event |