Spring event driven model--application of observer pattern in spring

Source: Internet
Author: User
Tags event listener

The Event-driven model in spring, also known as the Publish-subscribe pattern, is a typical application of the observer pattern, as summarized in the previous blog post, http://www.cnblogs.com/fingerboy/p/5468994.html Here's a look at the application of the observer pattern in Spring.

The structure of the spring Event-driven model.

  

Start by clarifying the concepts of several spring-provided classes

1.ApplicationEvent
 public Abstract classApplicationeventextendsEventObject {Private Static Final LongSerialversionuid = 7099057708183571937L; Private Final Longtimestamp;  publicapplicationevent (Object Source) {Super(source);  this. Timestamp =System.currenttimemillis (); }     public Final LongGettimestamp () {return  this. timestamp; }}

Applicationevent inherits from the EventObject of the jdk, all events need to inherit applicationevent, And the source of the event is obtained through SOURCE. the Class's implementation class Applicationcontextevent represents the Applicaitoncontext container Event.

2.ApplicationListener
 public Interface extends extends eventlistener {    void  onapplicationevent (E event);}

Applicationlistener inherits from the Jdk's eventlistener, all listeners have to implement this interface, this interface has only one onapplicationevent () method, The method accepts a applicationevent or its subclass object as a parameter, and in the method body, it can be processed by different judgment of the event class. when an event is triggered, all listeners receive a message, and if you need to request a listener's order of receipt, however, an implementation of this interface is implemented smartapplicationlistener, which allows you to specify the order in which listeners receive Events.

3.ApplicationContext

The implementation of the event mechanism requires three parts, event source, event, event listener, The applicationevent described above is equivalent to the event, Applicationlistener equivalent to the event listener, The source of the event here is that Applicaitoncontext.

ApplicationContext is the global container in spring, which translates to the meaning of the "application context", which is responsible for reading the Bean's configuration document, managing the Bean's loading, maintaining the dependency between the beans, and being responsible for the entire life cycle of the Bean. A little more popular is what we call the IOC container.

Application as an event source, you need to display the call Publishevent method, passing in a Applicationevent implementation class object as a parameter, Every time ApplicationContext publishes applicationevent, all Applicationlistener are automatically triggered.

The ApplicationContext interface implements the Applicationeventpublisher interface, which has a very important method:

 public Interface applicationeventpublisher {    void  publishevent (applicationevent event);}

Our common ApplicationContext have inherited the abstractapplicationcontext, like our usual classpathxmlapplicationcontext, Xmlwebapplicationcontex also inherited it, Abstractapplicationcontext is an abstract implementation class for ApplicationContext interfaces that implements the Publishevent method in this class.

 public void publishevent (applicationevent event) {        "event must not being null");         if (logger.istraceenabled ()) {            logger.trace ("publishing event in" + getdisplayname () + ":" + event); 
    
     }        getapplicationeventmulticaster (). multicastevent (event);        
     if (thisnull) {            this. parent.publishevent (event);        }    }

In this method, we see a getapplicationeventmulticaster (). this is going to involve another class of applicationeventmulticaster.

4.ApplicationEventMulticaster

belongs to the event broadcaster, and its role is to broadcast the event published by ApplicationContext to all Listeners.

There is a Applicationeventmulticaster member variable in Abstractapplicationcontext that provides the registration method for the listener Listener.

PublicAbstract classAbstractapplicationcontextextendsDefaultresourceloaderImplementsconfigurableapplicationcontext, Disposablebean {PrivateApplicationeventmulticaster applicationeventmulticaster; protected voidregisterlisteners () {//Register statically specified listeners First.         for(applicationlistener<?>listener:getapplicationlisteners ())        {getapplicationeventmulticaster (). Addapplicationlistener (listener); }        //Do not initialize Factorybeans here:we need to leave all regular beans//uninitialized to let post-processors apply to them!string[] listenerbeannames = Getbeannamesfortype (applicationlistener.class,true,false);  for(String lisname:listenerbeannames) {getapplicationeventmulticaster (). Addapplicationlistenerbean (lisName        ); }    }}
Demo using the event listener mechanism in spring

1. Create event class, inherit Applicationevent

 public class extends applicationevent {    public  myevent (Object source) {        Super(source);        System.out.println ("my Event");    }      public void Print () {        System.out.println ("hello spring event[myevent]");}    }

2. Set up the listening class to implement the Applicationlistener interface

 public class MyListener  implements  applicationlistener{        publicvoid   Onapplicationevent (applicationevent event) {        ifinstanceof  myevent) {            System.out.println ("into My Listener");            MyEvent myevent=(myevent) event;            Myevent.print ();     }}}

WE'LL build a listening class Here.

 public class MyListener  implements  applicationlistener{        publicvoid   Onapplicationevent (applicationevent event) {        ifinstanceof  myevent) {            System.out.println ("into My Listener");            MyEvent myevent=(myevent) event;            Myevent.print ();     }}}

3. Create a class that publishes the event, which implements the Applicationcontextaware interface, gets the ApplicationContext object, and publishes the event using the Publishevent method of the Object.

 public classMypubisherImplementsApplicationcontextaware {PrivateApplicationContext applicationcontext;  public voidSetapplicationcontext (applicationcontext Applicationcontext)throwsbeansexception { this. applicationcontext=applicationcontext; }     public voidpublishevent (applicationevent event) {System.out.println ("into My Publisher ' s method");    Applicationcontext.publishevent (event); }}

3. In the spring configuration file, the event class and the listener class are registered, and of course the annotations are used in the same way. Slightly

4. Testing

 public class MyTest {    publicstaticvoid  main (string[] Args) {        applicationcontext Context=new classpathxmlapplicationcontext ("classpath:spring/application-database.xml");        Mypubisher mypubisher= (mypubisher) context.getbean ("mypublisher");        Mypubisher.publishevent (new myevent ("1"));     }}

viewing console printing

My Event

Into My Publisher ' s method

Into My Listener
Hello Spring event[myevent]
into My second Listener
Hello Spring event[myevent]

Summarize

The spring Event-driven model uses the Observer pattern

ApplicationContext event processing can be implemented by Applicationevent abstract classes and Applicationlistener interfaces

When the listener is dealing with an event, it usually determines whether the incoming event is what it wants to handle, using the instanceof keyword

Applicationeventmulticaster event broadcaster realizes the registration of listeners, generally do not need us to implement, only need to display the call applicationcontext.publisherevent method can be

Spring event driven model--application of observer pattern in spring

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.