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


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) {  
  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) { = 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) {

	public void registerObserver(Student observer) {

	public void unRegisterObserver(Student observer) {

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

Step 3:

We have event and 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 {

	public void onApplicationEvent(Student event) {


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=""  
      xmlns:xsi="" xmlns:context=""  
      <bean id="customEventPublisher" class="com.event.model.Subject" />  
      <bean id="customEventHandler" class="com.event.model.EventReceiverHandler" />  

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);  
  Student obs2 = new Student(subject);  
  Student obs3 = new Student(subject);  
  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.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 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=""  
      xmlns:xsi="" xmlns:context=""  
  <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 id="applicationEventMulticaster"   
    <property name="taskExecutor" ref="taskExecutor" />;   
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





Popular posts from this blog

Get Browser Name and Version in Javascript

JQuery stopped providing $.browser function after 1.9 release.So you have to write your own code to get know browser and its version.There is not standard procedure or code to achieve this.
But I will show you to get browser name and version of  IE > 6, Google Chrome And FF.

Here we have AGENT to rescue.Every browser has navigation object available in its script.In this object userAgent field contains current browser information.

So you can ask me What is User-Agent?How will it help us?
          As I said earlier it contain browser information.There is not standard to show each information but almost every browser support it.
    There is complicated history behind user-agent variable.But in simple sense we can say that user-agent is used by server side component to get information of client-side browser and its compatibility to page it will going to rendered.So we conclude that this user-agent information is little bit 50% same in all browser.

Why is it(user-agent) 50% s…

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

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…