Spring publishes and receives custom events (Spring event propagation) [go]

Source: Internet
Author: User
Tags event listener stub

There is an event, that is, an event listener. Someone asks you what the spring listener looks for and you know it. Event Propagation ApplicationContext is based on the Observer pattern (the corresponding implementation in the Java.util package), which provides event propagation capabilities for the bean. Through application. Publishevent method, we can notify the system of all the Applicationlistener in the event. A typical application of event propagation is that when an operation in a Bean is an exception (such as a database connection failure), the exception listener is notified through the event propagation mechanism for processing. In the author of a project, has been the use of event mechanisms, better realize when the system is abnormal when the alarm on the monitoring terminal, while sending alarm SMS to the Administrator mobile phone function.

The ApplicationContext container provides the container internal event publishing function, which is inherited from the Javase standard custom event class.

Javase Standard custom event structure is not described in detail here, a picture is very straightforward to describe clearly:

EventObject, the base class for event types provided for Javase, any custom events are inherited from the class, such as the gray-to-right events in the middle. Subclass Applicationevent for this interface is provided in spring.

EventListener provides an event listener interface for Javase, and any custom event listener implements the interface, such as the individual event listeners on the left. The subclass Applicationlistener interface for this interface is provided in spring.

The role class for event publishers is not available in javase, and the role of event publishers is implemented by each application itself. Spring provides the Applicationeventpublisher interface as an event publisher, and ApplicationContext implements this interface, which acts as the publisher of events. But ApplicationContext differs in implementation, and spring provides the Applicationeventmulticaster interface, Responsible for managing Applicationlistener and releasing Applicationevent. ApplicationContext will delegate the corresponding event-related work to the Applicationeventmulticaster interface implementation class. The class diagram looks like this:

The event release sequence diagram is as follows:

-------------------------------------------------------------------------------------------------

Spring provides some aware related interfaces, Beanfactoryaware, Applicationcontextaware, Resourceloaderaware, Servletcontextaware, etc. One of the most commonly used is applicationcontextaware. The bean that implements Applicationcontextaware will be injected into the ApplicationContext instance after the bean is initially initialized. Applicationcontextaware provides the Publishevent () method, an event propagator that implements the Observer (Observer) design pattern, and provides event propagation capabilities for the bean. With the Application.publishevent method, we can notify all applicationlistener in the system of the event.

Spring Event Handling General procedure:

Defines the event class, inheriting org.springframework.context.ApplicationEvent.
Write the Publish event class Publisher to implement the Org.springframework.context.ApplicationContextAware interface.
Override Method Setapplicationcontext (ApplicationContext ApplicationContext) and publish method publish (Object obj).
Define time Listener class EventListener, implement Applicationlistener interface, implement method Onapplicationevent (Applicationevent event).

1. The publisher of the release 1.1 event needs to implement the interface Org.springframework.context.ApplicationEventPublisherAware 1.2 code example

ImportOrg.Springframework.Context.Applicationeventpublisher;ImportOrg.Springframework.Context.Applicationeventpublisheraware;/**** @author ZQ**/Public Class HelloWorld Implements Applicationeventpublisheraware{ Private StringWord; Private ApplicationeventpublisherTradeeventpublisher; Public voidSetword(StringW){ This.Word=W; } Public voidSay(){ System.Out.println("Say:"+ This.Word); Construct a tradeevent instance and publish it TradeeventTradeevent= New Tradeevent(New String("Tradeevent")); This.Tradeeventpublisher.Publisheventtradeevent} @Override public< Span class= "PLN" > void Setapplicationeventpublisher ( applicationeventpublisher Applicationeventpublisher { //TODO Auto-generated method Stub this.= Applicationeventpublisher;}} /span>

2. Accept Event 2.1 interface required to implement Org.springframework.context.ApplicationListener 2.2 code example

ImportOrg.Springframework.Context.Applicationevent;ImportOrg.Springframework.Context.Applicationlistener;ImportOrg.Springframework.Context.Event.Contextstartedevent;Public Class Tradecontextlistener Implements Applicationlistener{ @Override Public voidOnapplicationevent(ApplicationeventE) { System.Out.println(E.GetClass().Tostring()); TODO auto-generated Method Stub If (Einstanceof Contextstartedevent){ System.out. Println ( "it was contextstartedevent" Span class= "pun" >} if ( e instanceof tradeevent system.. Println (e. Getsource } }} /span>

3 Configuration Files

<?XML version="1.0"Encoding="Utf-8"?><! DOCTYPE beans Public "-//spring//dtd bean//en" "Http://www.springframework.org/dtd/spring-beans.dtd" ><beans> <bean Name= "HelloWorld" class=< Span class= "ATV" > "study". HelloWorld "> <propertyname= "word" value< Span class= "pun" >= "Hello World" /> < /bean> <bean id= "Tradecontextlistener" class= "study. Tradecontextlistener "/></BEANS>

4. Test code

ImportOrg.Springframework.Context.ApplicationContext;ImportOrg.Springframework.Context.Support.Classpathxmlapplicationcontext;ImportStudy.HelloWorld;Public Class Testhelloworld { /*** @param args*/ Public Static voidMain(String[]Args) { TODO auto-generated Method Stub applicationcontext ApplicationContext =< Span class= "PLN" > new classpathxmlapplicationcontext "study-context.xml" helloworld Bean = ( Span class= "Typ" >helloworld) applicationcontext. "HelloWorld" bean say (); }} /span>

The ApplicationContext event mechanism in spring---a default event) has already defined five standard events in spring, respectively, as follows:

1) Contextrefreshedevent: This event is triggered when ApplicationContext is initialized or refreshed.

2) Contextclosedevent: This event is triggered when ApplicationContext is closed. When a container is closed, all the singleton beans it manages are destroyed.

3) Requesthandleevent: In a Web application, the event is triggered when an HTTP request is terminated.

conteststartedevent:spring2.5 a new event that is triggered when the container invokes the Configurableapplicationcontext start () method to begin/Restart the container.

5) conteststopedevent:spring2.5 new event that is triggered when the container calls Configurableapplicationcontext's Stop () method to stop the container.

Here's an example of how to handle spring-default events (routine 3.8). Create a Java project, add spring development capabilities, and new Ioc.test package. Create a new Applicationeventlistener class in the package, implement the Applicationlistener interface, and add the event-handling code in the Onapplicationevent () method, as follows:

1 package ioc.test;
2
3//import omitted
4 Publicclass applicationeventlistenerimplements Applicationlistener {
5
6 publicvoid onapplicationevent (Applicationevent event) {
7
8//If container Refresh Event
9 if (eventinstanceof contextclosedevent) {
Ten System.out.println (Event.getclass (). Getsimplename () + "event has occurred! ");
}elseif (eventinstanceof contextrefreshedevent) {//If it is a container shutdown event
System.out.println (Event.getclass (). Getsimplename () + "event has occurred! ");
}elseif (eventinstanceof contextstartedevent) {
System.out.println (Event.getclass (). Getsimplename () + "event has occurred! ");
}elseif (eventinstanceof contextstoppedevent) {
System.out.println (Event.getclass (). Getsimplename () + "event has occurred! ");
}else{
System.out.println ("Other events have occurred:" +event.getclass (). GetName ());
19}
20
21}
22
23}
24

Define a bean in the spring configuration file, class Applicationeventlistener, with the following code:

1 <?xml version= "1.0" encoding= "UTF-8"?>
2 <beans .......
3
4 <bean id= "Applicationeventlistener" class= "Ioc.test.ApplicationEventListener"/>
5
6 </beans>
7

Add the Tesmain class containing the main method, in the main method, call the appropriate method of the container, triggering the spring default event, the code is as follows:

1 package ioc.test;
2
3//import omitted
4 Publicclass Tesmain {
5
6 publicstaticvoid Main (string[] args) {
7 Abstractapplicationcontext ac=new classpathxmlapplicationcontext ("Applicationcontext.xml");
8
9
//Ac.refresh ();//Trigger Contextrefreshedevent Event
Ac.start ();//Trigger Contextstartedevent Event
Ac.stop (); Triggering contextstoppedevent Events
Ac.close ();//close container, trigger Contextclosedevent Event
14
15}
16}
17

To run the main class, the console output is as follows:


As you can see from the example, to register an event listener, we just need to configure it as a bean, and the ApplicationContext container will automatically register it

Spring publishes and receives custom events (Spring event propagation) [go]

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.