Comment-driven event listener in Spring framework

Source: Internet
Author: User

Event interaction has become an integral part of many applications, and the spring Framework provides a complete infrastructure to handle transient events. Let's take a look at the note-driven event listener in the Spring 4.2 framework.

1, the early way

In the early days, the component had to get notified from the spring event about the custom domain event, then the component had to implement the Applicationlistener interface and overwrite the Onapplicationevent method.

@Component class Implements Applicationlistener<OldWayBlogModifiedEvent> {        @Override    public  void  Onapplicationevent (oldwayblogmodifiedevent event) {        Externalnotificationsender.oldwayblogmodified (event);    }}

The code above works fine, but it creates a new class for each event, causing code bottlenecks.

In addition, our event class inherits the event base class in the Applicationevent class--spring application.

class extends Applicationevent {
Public oldwayblogmodifiedevent (blog) { super(blog); }
Public Blog Getblog () { return (blog) getsource (); }}
2. Note-driven event listener

The Spring 4.2 Framework is notable for annotating any of the spring components with annotations @eventlistener.

@EventListener  Public void blogmodified (blogmodifiedevent blogmodifiedevent) {    externalnotificationsender.blogmodified ( blogmodifiedevent);}

Spring creates an Applicationlistener instance of the event and gets the type of the event from the method parameter. There is no limit to the number of methods in a class that are commented by the event, and all related event handles are grouped into a class.

3. Conditional Event Handling

To make annotation @eventlistener more powerful, Spring 4.2 supports the way an event type is expressed with an spel expression. Suppose the following is an event class:

 Public classBlogmodifiedevent {
Private FinalBlog Blog; Private Final BooleanImportantchange;
Publicblogmodifiedevent (Blog blog) { This(Blog,false); } PublicBlogmodifiedevent (Blog blog,BooleanImportantchange) { This. Blog =blog; This. Importantchange =Importantchange; } PublicBlog Getblog () {returnblog; } Public BooleanIsimportantchange () {returnImportantchange; }}

It is important to note that in real-world applications there may not be a hierarchy of events such as this article.
Also note that it is easier to write in groovy.

Using condition parameters to illustrate events, the important changes are:

@EventListener (condition = "#blogModifiedEvent. Importantchange")publicvoid  Blogmodifiedspel (Blogmodifiedevent blogmodifiedevent) {
Externalnotificationsender.blogmodifiedspel (blogmodifiedevent);
}
4. Hierarchy of Loose event types

Prior to Spring 4.2, Applicationeventpublisher only has the ability to publish its inherited objects after the Applicationevent event. At the beginning of Spring 4.2, this interface has been extended to support arbitrary object types. In this case, the object is encapsulated into payloadapplicationevent and sent by.

// base class with Blog field-no need to extend ' applicationevent ' class baseblogevent {} class extends baseblogevent {} // somewhere in the code Applicationeventpublisher publisher = (...);    // injectedpublisher.publishevent (new//just plain instance of the event

This change makes it easier to publish events. On the other hand, however, it can cause event tracking to become more difficult, especially in large applications.

5. Responding to publishing events

Note @eventlistener There is also a point to notice that spring automatically publishes the returned event when the non-null return type.

@EventListener  Public blogmodifiedresponseevent blogmodifiedwithresponse (blogmodifiedevent blogmodifiedevent) {
Externalnotificationsender.blogmodifiedwithresponse (blogmodifiedevent);
return New blogmodifiedresponseevent ( blogmodifiedevent.getblog (), BlogModifiedResponseEvent.Status.OK);}
6. Asynchronous Event Processing

Note @eventlistener can also be used in combination with annotation @async to provide a mechanism for asynchronous event handling. In the following code, the specified event listener does not block the main code execution and is not handled by other listeners.

@Async    //Remember To enable asynchronous method execution           //inyour Application with @EnableAsync@EventListenerpublicvoid  Blogaddedasync ( Blogaddedevent blogaddedevent) {    externalnotificationsender.blogadded (blogaddedevent);}

In order for the work to be performed asynchronously, it is often necessary to use the annotation @enableasync in the context of the spring project.

or an XML file:

<!--open Asynchronous call @async annotations--><task:annotation-driven executor= "Mytaskexecutor"/><task:executor id= " Mytaskexecutor "pool-size=" 5 "/>
7. Summary

Note-driven event listener is a new feature introduced in spring Framework version 4.2, which reduces boilerplate code for spring projects, making the code more flexible, especially when the need for a small number of events is apparent.

Detailed Comment-driven event listener in Spring framework

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.