Java Login

About javalogin.com

Hello guys,
javalogin.com is for Java and J2EE developers, all examples are simple and easy to understand 

It is developed and maintained by Vaibhav Sharma. The views expressed on this website are his own and do not necessarily reflect the views of his former, current or future employers. I am professional Web development. I work for an IT company as Senior Consultant. Primary I write about spring, hibernate and web-services. I am trying to present here new technologies.


     << Previous
Next >>     


Spring Event Handling

Event Handling is important feature of spring. Not a spring, but Generally any event handling consist of three core component:

  • Event Publisher entity which publish event
  • Event Listener entity which listen event
  • Event itself is a class that contain information about event

Spring allow you to handle events triggered by the framework. An Event is triggered because of the state change or some activities with in the container. For eg, Spring triggers ContextClosedEvent when the ApplicationContext is closed. If you want to do some house keeping activities on events, then you can listen to those events through a listener and do your stuff. Spring event mechanism is based on the standard Observer design pattern.

Spring provides ApplicationEvent class and ApplicationListener interface to support event handling. If you want to handle an event, then create a bean by implement ApplicationListener interface and plugin that bean to the ApplicationContext. Spring will recognize such beans and everytime an event (which is a sub class of ApplicationEvent) is published to the ApplicationContext, your bean will be notified.

Below are the standard events provided by Spring as per Spring Framework Reference.

ContextRefreshedEvent Published when the ApplicationContext is initialized or refreshed, for example, using the refresh() method on the ConfigurableApplicationContext interface. "Initialized" here means that all beans are loaded, post-processor beans are detected and activated, singletons are pre-instantiated, and the ApplicationContext object is ready for use. As long as the context has not been closed, a refresh can be triggered multiple times, provided that the chosen ApplicationContext actually supports such "hot" refreshes. For example, XmlWebApplicationContext supports hot refreshes, but GenericApplicationContext does not.
ContextStartedEvent Published when the ApplicationContext is started, using the start() method on the ConfigurableApplicationContext interface. "Started" here means that all Lifecycle beans receive an explicit start signal. Typically this signal is used to restart beans after an explicit stop, but it may also be used to start components that have not been configured for autostart , for example, components that have not already started on initialization.
ContextStoppedEvent Published when the ApplicationContext is stopped, using the stop() method on the ConfigurableApplicationContext interface. "Stopped" here means that all Lifecycle beans receive an explicit stop signal. A stopped context may be restarted through a start() call.
ContextClosedEvent Published when the ApplicationContext is closed, using the close() method on the ConfigurableApplicationContext interface. "Closed" here means that all singleton beans are destroyed. A closed context reaches its end of life; it cannot be refreshed or restarted.
RequestHandledEvent A web-specific event telling all beans that an HTTP request has been serviced. This event is published after the request is complete. This event is only applicable to web applications using Spring's DispatcherServlet.

Example of Spring Events

Employee.java

package eventListener;

public class Employee {
private int id;
private String name;

public void displayEmployeeDetail() {
System.out.println("Employee Id :: "+getId()
+" and Employee Name :: "+getName());
}

public int getId() {
return id;
}

public void setId(int id) {
this .id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this .name = name;
}

}

context.xml

........
........
<bean id="emp" class="eventListener.Employee">
<property name="id" value="1" />
<property name="name" value="Test" />
</bean>

<context:annotation-config/>
<context:component-scan base-package="eventListener"/>
</beans>

MyEventListener.java

package eventListener;

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

@Component
public class MyEventListener implements ApplicationListener {

@Override
public void onApplicationEvent(ApplicationEvent event) {
System.out.println(event.toString());

}

}

Main.java

package eventListener;

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

public class Main {

public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext
("eventListener/context.xml");
Employee e = (Emp)context.getBean("emp");
e.displayEmployeeDetail();
}
}

When you run above program you will get below output:
org.springframework.context.event.ContextRefreshedEvent
[source=org.springframework.context.support.ClassPathXmlApplicationContext@ab50cd: startup date
[Tue Oct 07 09:43:13 IST 2014]; root of context hierarchy]
1 Test

Here you can see that an event called has been printed here ContextRefreshedEvent that has been published. And our listen class listen to this event and printed toString(). Here you can see startup date and root hierarchy. This message is toString of contextRefreshEvent and this event is published by spring framework and listener class listen this event. So this is simple way to publish event.

Now if you want to publish your own event, then there are two things to publish your own event class

  1. we need to have an event class
  2. we need to write your own class

Now I wan to publish an event on displayEmployeeDetail() method in Employee class. So First I have to create EmployeeDetailEvent class and second step is I need to publish that in my displaymethod.

DisplayDetailEvent.java

package eventListener;

import org.springframework.context.ApplicationEvent;

public class DisplayDetailEvent extends ApplicationEvent{

public DisplayDetailEvent(Object source) {
super (source);
// TODO Auto-generated constructor stub
}

@Override
public String toString() {
return "Display Event Occured";
}

}

Employee.java

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

public class Employee implements ApplicationEventPublisherAware{
private int id;
private String name;
private ApplicationEventPublisher publisher;

public void displayEmployeeDetail() {
System.out.println("Employee Id :: "+getId()
+" and Employee Name :: "+getName());

DisplayDetailEvent displayDetailEvent = new DisplayDetailEvent(this);
publisher.publishEvent(displayDetailEvent);
}

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

public int getId() {
return id;
}

public void setId(int id) {
this .id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

}

Here you can see when you run this program Display Event Occured message will be printed. What is actually happening the context is initialized, context message comes up here, code run then publishing code run, displayDetails method run and onApplicationEvent method called from MyEventListener class and display event pass from here and display message Display Event Occured message display.


     << Previous
Next >>