Reading:  

Quick to the point introduction to Spring Framework


Event Handling

Event Handling in Spring

The life cycle of the beans completely manages by the ApplicationContext, ApplicationContext of Event handling is provided through the ApplicationEvent class and ApplicationListener interface. So bean implements the ApplicationListener, then every time an ApplicationEvent gets published to the ApplicationContext, that bean is notified.

Built-in Events of Spring:

  • ContextClosedEvent:
    This event is called when the ApplicationContext is closed using the close() method on the ConfigurableApplicationContext interface.
  • RequestHandledEvent:
    This is a web-specific event telling all beans that an HTTP request has been serviced.
  • ContextRefreshedEvent:
    When the ApplicationContext is initialized or refreshed this event is called.
  • ContextStoppedEvent:
    When the ApplicationContext is stopped using the method stop() on the interface ConfigurableApplicationContext this event is published.
  • ContextStartedEvent:
    When the ApplicationContext is started using the method start() on the interface ConfigurableApplicationContext this event is published.

Listening to Context Events:

To listen a context event, a bean should implement the ApplicationListener interface which has just one method onApplicationEvent().

Example:

Java file: Student

package pack1;

public class Student {
	private String sname;

	public void setName(String sname) {
		this.sname = sname;
	}
	public void getMessage() {
		System.out.println("Name : " + sname);
	}
}

Java file: StartEventHandlerExample

package pack1;

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextStartedEvent;

public class StartEventHandlerExample 
   implements ApplicationListener{

   public void onApplicationEvent(ContextStartedEvent event) {
      System.out.println("Inside onApplicationEvent of StartEventHandler");
   }
}
 

Java file: StopEventHandlerExample

package com.tutorialspoint;

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextStoppedEvent;

public class StopEventHandlerExample
implements ApplicationListener < ContextStoppedEvent > {

	public void onApplicationEvent(ContextStoppedEvent event) {
		System.out.println("Inside onApplicationEvent of StopEventHandler ");
	}
}

Java file: ExmTest

package pack1;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.*;

public class MainApp {
	public static void main(String[] args) {

		ConfigurableApplicationContext con = new ClassPathXmlApplicationContext("Beans.xml");

		// to raise a start event.
		con.start();

		Student st = (Student) con.getBean("student");
		st.getName();

		// to raise a stop event.
		con.stop();
	}
}

 

XML 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="student" class="pack1.Student">
       <property name="sname" value="Nimrit"/>
   </bean>

   <bean id="StartEvent" 
         class="pack1.StartEventHandlerExample"/>

   <bean id="StopEvent" 
         class="pack1.StopEventHandlerExample"/>
</beans>

 

Compile and run the program will get the below result:


Result:

InsideonApplicationEvent ofStartEventHandler Name : Nimrit
Inside onApplicationEvent of StopEventHandler

 

Custom Events

User need to follow the steps to write and publish custom events. 

Example:

Create a class, MyEvent by extending ApplicationEvent.

package pack1;

import org.springframework.context.ApplicationEvent;

public class MyEvent extends ApplicationEvent {

	public MyEvent(Object source) {
		super(source);
	}
	public String toString() {
		return "User created My Event";
	}
}

 

To publish event class which is defined above from any class, class MyEventPublisher which implements ApplicationEventPublisherAware.

package pack1;

import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;

public class MyEventPublisher implements ApplicationEventPublisherAware {
   
   private ApplicationEventPublisher appPublisher;

   public void setAppEventPublisher (ApplicationEventPublisher appPublisher){
               this.appPublisher = appPublisher;
   }

   public void display() {
      MyEvent my = new MyEvent(this);
      appPublisher.publishEvent(my);
   }
}
 

To handle published event in a class, class EventClassHandler which implements interface ApplicationListener and implements onApplicationEvent method.

package pack1;

import org.springframework.context.ApplicationListener;

public class MyEventHandler implements ApplicationListener{

   public void onApplicationEvent(MyEvent eve) {
      System.out.println(eve.toString());
   }
}
 

Create an AppTest class which will work as Spring application:

package pack1;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AppTestSS {
   public static void main(String[] args) {
   ConfigurableApplicationContext con = 
new ClassPathXmlApplicationContext("Beans.xml");
	  
      CustomEventPublisher eventp = 
      (MyEventPublisher)con.getBean("myEventPublisher");
      eventp.publish();  
         }
}
 

Create beans 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="myEventHandler" 
      class="pack1.MyEventHandler"/>

   <bean id="myEventPublisher" 
      class="pack1.MyEventPublisher"/>
</beans>

 

Compile and run the program will get the below result:


Result:

User created My Event

Description

This tutorial covers various topics releated to Spring Framework as listed below

  • Framework Overview
  • Modules
  • Environment Setup
  • Saying Hello World with Spring
  • IoC Containers
  • Bean Definition
  • Bean Scopes 
  • Bean Life Cycle
  • Bean Post Processors
  • Bean Definition Inheritance
  • Dependency Injection
  • Injecting Inner Beans
  • Injecting Collection
  • Beans Auto-Wiring
  • Annotation Based Configuration
  • Java Based Configuration
  • Event Handling in Spring
  • Custom Events in Spring
  • JDBC Framework Overview
  • Transaction Management

 

 



Prerequisites

Prior knowledge of Java is essential

Audience

Beginners or students seeking quick introduction to Spring

Learning Objectives

This tutorial is for beginners seeking quick introduction to Spring Framework.

Author: Subject Coach
Added on: 22nd Jun 2015

You must be logged in as Student to ask a Question.

None just yet!