Skip to main content

Spring Custom Event Handling Tutorial

What are spring Custom Events?

Spring Framework provides in-built API for context management and even for custom event creation for you.

Spring Event management follows Observer Design Pattern. In observer Design pattern there is loose coupling between objects.There three main components it has

                     1 .Publisher object which publish event/call event 

                     2. Listener object which listens the event that occurred

                     3. Event object which used to communicate

e.g:

an event publisher (subject) object can communicate with other objects without knowing which object is listening and event listener (handler) can work with event without knowing which object published the event.

 

What is use of of creating custom Event?

Mostly we take in consideration of custom event when we want to do some notifications.

e.g. One can write Blog (Publisher),People subscribe the blogs (Listener)when new content added in blog,all people who subscribed this blog will get notified.In system scenario,Email Or SMS notification are real examples. 

 

I will explain demo of Spring Custom Event in step wise manner.

 

Step 1:

First create the Event that will Listen.To create custom event in spring ,your class should extend ApplicationEvent. 

Here we have student who are communicated and are the listener.

 

 public class Student extends ApplicationEvent {  
  private static final long serialVersionUID = 1L;  
  private String dataReceived;  
  private Subject subject;  
  private String name;  
  public Student(Object source) {  
  super(source);  
  subject=(Subject) source;  
  dataReceived="No Content";  
  }  
  public String showContent(){  
  this.dataReceived = (subject.getSendData()!=null && !subject.getSendData().equals(""))?subject.getSendData():dataReceived;  
  return "Student "+name+" received "+dataReceived;  
  }  
  public void setName(String name) {  
  this.name = name;  
  }  
 }  

 

Step 2:

Now the publisher which will publish events to listener.In spring ,to create custom publish,our class should implement ApplicationEventublisherAware Interface.

Here,we have subject which which will send message to students.It will publish the event. 

 

 public class Subject implements ApplicationEventPublisherAware {

	private ApplicationEventPublisher applicationEventPublisher;
	private List studentList;
	private String sendData;

	public Subject() {
		studentList = new ArrayList();
	}

	public String getSendData() {
		return sendData;
	}

	public void setSendData(String sendData) {
		this.sendData = sendData;
	}

	public void publish() {
		for (Student observer : studentList) {
			applicationEventPublisher.publishEvent(observer);
		}
	}

	public void registerObserver(Student observer) {
		studentList.add(observer);
	}

	public void unRegisterObserver(Student observer) {
		studentList.remove(observer);
	}

	@Override
	public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
		this.applicationEventPublisher = applicationEventPublisher;
	}
}


Step 3:
 

We have event and publisher.now we will define Listener which will continuously listen each event.In spring ,our Listener should implement the interface ApplicationListener which is of our custom type .
Here we have  EventReceiverHandler,will will receive each event.



public class EventReceiverHandler implements ApplicationListener {

	@Override
	public void onApplicationEvent(Student event) {
		System.out.println(event.showContent());
	}

}




Step 4:
Here is the actual magic, when we register our Receiver/handler in spring context,all events will filtered by spring and listeners will get invoked for matching event. 

Here we have bean.xml.

 <beans xmlns="http://www.springframework.org/schema/beans"  
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"  
      xmlns:task="http://www.springframework.org/schema/task"  
      xsi:schemaLocation="http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
      <bean id="customEventPublisher" class="com.event.model.Subject" />  
      <bean id="customEventHandler" class="com.event.model.EventReceiverHandler" />  
 </beans>  

Step 5:
Now create Application context And publish event.


  // custom event in spring  
  ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");  
  Subject subject = (Subject) context.getBean("customEventPublisher");  
  Student obs1 = new Student(subject);  
  obs1.setName("1");  
  Student obs2 = new Student(subject);  
  obs2.setName("2");  
  Student obs3 = new Student(subject);  
  obs3.setName("3");  
  subject.registerObserver(obs1);  
  subject.registerObserver(obs2);  
  subject.registerObserver(obs3);  
  System.out.println("-----------First Publish-------------");  
  subject.publish(); //publish event  
  System.out.println("-----------Second Publish-------------");  
  subject.setSendData(" Hello Buddy !");  
  subject.publish(); //publish event  
  System.out.println("-----------Third Publish-------------");  
  subject.unRegisterObserver(obs2);  
  subject.setSendData(" Thanks Buddy !");  
  subject.publish(); //publish event  

That's it.We have implemented spring custom event .

Output is self explanatory.

 -----------First Publish-------------  
 Student 1 received No Content  
 Student 2 received No Content  
 Student 3 received No Content  
 -----------Second Publish-------------  
 Student 1 received Hello Buddy !  
 Student 2 received Hello Buddy !  
 Student 3 received Hello Buddy !  
 -----------Third Publish-------------  
 Student 1 received Thanks Buddy !  
 Student 3 received Thanks Buddy !  


Remember this is SYNCHRONIZED event Handling.If you want unsynchronised event  handling then,then what ? don't be panic spring is here for you.you have to just add SimpleApplicationEventMulticaster bean in your bean.xml along with TaskExcecutor specifing the number of Threads you want to use,.Event event will have its own separate Thread.

New bean.xml will be

  <?xml version="1.0" encoding="UTF-8"?>  
 <beans xmlns="http://www.springframework.org/schema/beans"  
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"  
      xmlns:task="http://www.springframework.org/schema/task"  
      xsi:schemaLocation="http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
  <bean id="customEventHandler" class="com.event.model.EventReceiverHandler" />;   
  <bean id="customEventPublisher" class="com.event.model.Subject" />;   
   <bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">;   
  <property name="corePoolSize" value="5" />;   
  </bean>   
  <bean id="applicationEventMulticaster"   
    class="org.springframework.context.event.SimpleApplicationEventMulticaster">;   
    <property name="taskExecutor" ref="taskExecutor" />;   
  <bean/>;   
 </beans>  
In short,we can say that

      Publisher  ----  {Loose coupling,Handled by Spring Context } ---- Observer

 

I have maintained tutorial as simple as possible by avoiding complex technical terms if in case you are not earlier aware. If you have any complaint or suggestion please mail me at oomph.fortuity@gmail.com

 

References:

http://docs.spring.io/spring/docs/2.5.x/api/org/springframework/context/ApplicationEventPublisherAware.html

 http://docs.spring.io/spring/docs/3.0.x/javadoc-api/org/springframework/context/ApplicationListener.html

http://docs.spring.io/spring/docs/2.0.x/api/org/springframework/context/ApplicationEvent.html
 

http://en.wikipedia.org/wiki/Observer_pattern

 

 



Popular posts from this blog

Share data between Iframe and its Parent using JQuery

There could be requirement that you have to pass variables values to Iframe from parent or in other scenario you have to pass values from Iframe to its parent.I am going to show simple example of above situation with the help of JQuery.
           Support we have parent HTML page having iframe included like below

<html> <body> <input id="parentValue" type="text" value="I am from Parent !" /> <iframe src="domainurl/relativepath" id="iframe"></iframe> <script> $(document).ready(function() { //code to take value from child iframe var childValue = $("#iframe").contents().find("#childValue").val(); alert(childValue); }); </script> </body> </html> 
        and we have frame code like below
<html> <body> <input id="childValue" type="text" value="I …

Spring Default Limit for Collection and Array is 256

If you are working in Web Application Development then you may stuck or already had ,then you will get mad of getting this error


java.lang.ArrayIndexOutOfBoundsException:Arrayindexoutofrange256
How this error emanates in Spring?

i will explain you with example.Suppose you are adding Values in List in JSP using JSTL tag or other.
This list is in Form(HTML).When you POST this form,In behind Stage,Spring does binding of Object and List if present.

But wait...
In Spring,Default limit for array and collection growing is 256.

Why this limit is Set?

seldom you have to send List size greater than this limit.
Spring has set this limit to avoid notable OutOfMemoryErrors in case of large indexes.

So,than What if i want to set Collection greater than this size?

I had told earlier,spring does binding behind.If we tell spring to increase it's size or set collection size behalf of spring.
You you can do it.

We have initBinder,  in Spring  it is called when spring does the binding mechanism
e.g @Mod…

Apache FOP Tutorial for PDF Generation

What is meant by Apache FOP?

Apache is providing open source JAVA application for PDF(or any other format) file generation from XML data.Simply to can give data in XML,it gives output in PDF or any format.But it is primary for PDF output.

Official explanation,
OP (Formatting Objects Processor) is the world's first print formatter driven by XSL formatting objects (XSL-FO) and the world's first output independent formatter. It is a Java application that reads a formatting object (FO) tree and renders the resulting pages to a specified output. Output formats currently supported include PDF, PCL, PS, SVG, XML (area tree representation), Print, AWT, MIF and TXT

How wcan configure apache fop with our project?

I am going to explain how to generate PDF using Apache FOP.
I will explain it in steps

Step 1:
You will require 3 jar for configurations.Here fop jar depend on both avalon api and avalon impl.
              1.    apache fop 1.1
              2.    avalon-framework-api 4.3.1
    …