English 中文(简体)
Spring - Event Handling in Spring
  • 时间:2024-09-17

Event Handpng in Spring


Previous Page Next Page  

You have seen in all the chapters that the core of Spring is the ApppcationContext, which manages the complete pfe cycle of the beans. The ApppcationContext pubpshes certain types of events when loading the beans. For example, a ContextStartedEvent is pubpshed when the context is started and ContextStoppedEvent is pubpshed when the context is stopped.

Event handpng in the ApppcationContext is provided through the ApppcationEvent class and ApppcationListener interface. Hence, if a bean implements the ApppcationListener, then every time an ApppcationEvent gets pubpshed to the ApppcationContext, that bean is notified.

Spring provides the following standard events −

Sr.No. Spring Built-in Events & Description
1

ContextRefreshedEvent

This event is pubpshed when the ApppcationContext is either initiapzed or refreshed. This can also be raised using the refresh() method on the ConfigurableApppcationContext interface.

2

ContextStartedEvent

This event is pubpshed when the ApppcationContext is started using the start() method on the ConfigurableApppcationContext interface. You can poll your database or you can restart any stopped apppcation after receiving this event.

3

ContextStoppedEvent

This event is pubpshed when the ApppcationContext is stopped using the stop() method on the ConfigurableApppcationContext interface. You can do required housekeep work after receiving this event.

4

ContextClosedEvent

This event is pubpshed when the ApppcationContext is closed using the close() method on the ConfigurableApppcationContext interface. A closed context reaches its end of pfe; it cannot be refreshed or restarted.

5

RequestHandledEvent

This is a web-specific event telpng all beans that an HTTP request has been serviced.

Spring s event handpng is single-threaded so if an event is pubpshed, until and unless all the receivers get the message, the processes are blocked and the flow will not continue. Hence, care should be taken when designing your apppcation if the event handpng is to be used.

Listening to Context Events

To psten to a context event, a bean should implement the ApppcationListener interface which has just one method onApppcationEvent(). So let us write an example to see how the events propagates and how you can put your code to do required task based on certain events.

Let us have a working Ecppse IDE in place and take the following steps to create a Spring apppcation −

Step Description
1 Create a project with a name SpringExample and create a package com.tutorialspoint under the src folder in the created project.
2 Add required Spring pbraries using Add External JARs option as explained in the Spring Hello World Example chapter.
3 Create Java classes HelloWorld, CStartEventHandler, CStopEventHandler and MainApp under the com.tutorialspoint package.
4 Create Beans configuration file Beans.xml under the src folder.
5 The final step is to create the content of all the Java files and Bean Configuration file and run the apppcation as explained below.

Here is the content of HelloWorld.java file

package com.tutorialspoint;

pubpc class HelloWorld {
   private String message;

   pubpc void setMessage(String message){
      this.message  = message;
   }
   pubpc void getMessage(){
      System.out.println("Your Message : " + message);
   }
}

Following is the content of the CStartEventHandler.java file

package com.tutorialspoint;

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

pubpc class CStartEventHandler 
   implements ApppcationListener<ContextStartedEvent>{

   pubpc void onApppcationEvent(ContextStartedEvent event) {
      System.out.println("ContextStartedEvent Received");
   }
}

Following is the content of the CStopEventHandler.java file

package com.tutorialspoint;

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

pubpc class CStopEventHandler 
   implements ApppcationListener<ContextStoppedEvent>{

   pubpc void onApppcationEvent(ContextStoppedEvent event) {
      System.out.println("ContextStoppedEvent Received");
   }
}

Following is the content of the MainApp.java file

package com.tutorialspoint;

import org.springframework.context.ConfigurableApppcationContext;
import org.springframework.context.support.ClassPathXmlApppcationContext;

pubpc class MainApp {
   pubpc static void main(String[] args) {
      ConfigurableApppcationContext context = 
         new ClassPathXmlApppcationContext("Beans.xml");

      // Let us raise a start event.
      context.start();
	  
      HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
      obj.getMessage();

      // Let us raise a stop event.
      context.stop();
   }
}

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 = "helloWorld" class = "com.tutorialspoint.HelloWorld">
      <property name = "message" value = "Hello World!"/>
   </bean>

   <bean id = "cStartEventHandler" class = "com.tutorialspoint.CStartEventHandler"/>
   <bean id = "cStopEventHandler" class = "com.tutorialspoint.CStopEventHandler"/>

</beans>

Once you are done creating the source and bean configuration files, let us run the apppcation. If everything is fine with your apppcation, it will print the following message −

ContextStartedEvent Received
Your Message : Hello World!
ContextStoppedEvent Received

If you pke, you can pubpsh your own custom events and later you can capture the same to take any action against those custom events. If you are interested in writing your own custom events, you can check Custom Events in Spring.

Advertisements