Use and analysis of custom event events in spring

Source: Internet
Author: User
Tags getmessage

In the project I am currently in touch with a lot of spring-related technology, the framework of spring, Spring MVC does not say, the details of the function also used a lot, such as Schedule timer task, filter filter, Interceptor interceptor, etc., And this one I'm going to say is Spring event custom events, the current project does not seem to be very useful, but this technology seems to be very important, so also can not be mastered.
For the explanation and understanding of the event-driven model, I think a blog post is very good, especially when explaining this relationship, the example of a traffic light is very pertinent, here is a simple explanation:

The event-driven model is what we often call an observer, or a publish-subscribe model, and some key points to understand it:
1. The first is a one-to-many relationship between objects, the simplest of which is the traffic light, the beacon is the target (party), and the pedestrian stares at the signal (multiple);
2. When the target sends a change (release), the Observer (Subscriber) can receive the change;
3. How the Observer handles (if the pedestrian is walking, walking/walking/not moving, the target does not control), the target does not need to intervene, so the relationship between them is loosely coupled.

The original address of the reference: http://xls9577087.iteye.com/blog/2121752 (This article also explains the orderly listening and disorderly listening, asynchronous events and so on, interested can also go there to learn about it)
When we have a simple understanding of the event driver, we can probably know when it should be used, and then to study how it should be used, the single text may not be easy to explain, or the code first, and then together to explain.

To first customize an event, you need to inherit the Applicationevent class, which is equivalent to installing a signal without power, no lights, need to have the basic characteristics of the signal.

 PackageSPRINGTEST5;ImportOrg.springframework.context.ApplicationEvent; Public  class eventtest extends applicationevent {    Private Static Final LongSerialversionuid =1LPrivateString message; Public eventtest(Object source, String message) {Super(source); This. message = message; } PublicStringGetMessage() {returnMessage } Public void Setmessage(String message) { This. message = message; }}

Then create a listener class, the equivalent of pedestrians (whether or not to use vehicles), the need to implement the Applicationlistener interface, and rewrite the Onapplicationevent method, it can be understood that the pedestrian need to see the signal, and can understand the meaning of the signal line. Otherwise, there is no difference between the lamp and no signal, and it is useless to read it without understanding it.

package springTest5;import org.springframework.context.ApplicationListener;import org.springframework.stereotype.Component;@Componentpublicclass ListenerTest1 implements ApplicationListener<EventTest> {    publicvoid onApplicationEvent(EventTest event) {        System.out.println("test1:" + event.getMessage());    }}

The annotations here simply declare a bean, which should not require much explanation.
then the third step naturally needs a control signal change of things, equivalent to connect him to the wire, give him a normal change of red and yellow green program and circuit.

package  Springtest5;import  org.springframework.beans.factory.annotation.Autowired; import  org.springframework.context.ApplicationContext; import  org.springframework.stereotype.Component;  @Component  public  class  eventpbulish  {      @Autowired  ApplicationContext context; public  void  publish  (String message) {context.publishevent (new  eventtest (this ,    message)); }}

Here, is actually finished, but it is clear that we do not have a reasonable configuration file, then the note here is not used by spring, is purely a device, so also need a configuration file, or equivalent configuration file configuration class, for the relevant class to take effect.

package springTest5;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;@Configuration@ComponentScan("springTest5")publicclass ConfigTest {}

For the meaning of the two annotations here, the previous days of the article has been explained many times, so here will not say, really do not know, you can turn a few days ago blog.
Here, the equivalent of we created a normal operation of the signal, created a normal pedestrian, but it is still motionless, we need to let him move up, that is, the main method of testing, the equivalent of letting pedestrians start to see the lights, so that the circuit began to power.

package springTest5;import org.springframework.context.annotation.AnnotationConfigApplicationContext;publicclass MainTest {    publicstaticvoidmain(String[] args) {        new AnnotationConfigApplicationContext(ConfigTest.class);        EventPbulish eventPbulish = context.getBean(EventPbulish.class);        eventPbulish.publish("zhangsan");        context.close();    }}

After running the main method, the result is as follows:

According to the above code can be known to represent the normal operation of the event, that is, the light is normally emitted, pedestrians received the message normally.
Then there is a detail that the traffic lights on the pedestrian, is a one-to-many relationship, then the event here is true? In order to verify, I then write a listener, and then new one pedestrian, everything else unchanged.

package springTest5;import org.springframework.context.ApplicationListener;@Componentpublicclass ListenerTest2 implements ApplicationListener<EventTest> {    publicvoid onApplicationEvent(EventTest event) {        System.out.println("tst2:" + event.getMessage());    }}

Run the main method again and the results are as follows: '

It is clear that two pedestrians are normally receiving signals from the signal.
So, based on the first explanation above, and then the example below, we should probably know what a complete event here contains: a goal, an event, an object to receive the target information, a listener, and a control to change or emit information.
Here basically even if it is finished, this is the simplest way to achieve, like some of the details of the configuration to change the configuration file and so on, can be their own appropriate variant.
At the end, combined with @propertysource annotations, I made a small variant of the above, simulating a person's broadcast, shouting a man's name, and then heard the person to answer accordingly.
The difference between this example and the top is that it adds a properties configuration to initialize the name of the receiving object, and practice @propertysource annotations by the way.

name1=zhangsanname2=lisi

Then you modify the listener class to get your name from the properties file.

Package SpringTest5;import org. Springframework. Beans. Factory. Annotation. Value;import org. Springframework. Context. Applicationlistener;import org. Springframework. Context. Annotation. Bean;import org. Springframework. Context. Annotation. Propertysource;import org. Springframework. Context. Support. Propertysourcesplaceholderconfigurer;import org. Springframework. Stereotype. Component;@Component @propertysource ("Test.properties") public class ListenerTest1 implements applicationlistener<eventtest> {@Value ("${name1}") String Name;public void Onapplicationevent (Eventtest event) {if (event. GetMessage(). Equals(name)) {System. out. println("You need to find"+ Event. GetMessage() +", yes, I am"+ name);} else {System. out                . println("You need to find"+ Event. GetMessage() +", but I 'm not"+ Event. GetMessage() +", I ' AM"+ name);}} @Bean public static Propertysourcesplaceholderconfigurer Propertyconfigure () {return new Propertysour Cesplaceholderconfigurer ();}}

where Propertyconfigure () is required, only to write this ability to just get the data from the properties, but after testing, this piece of code only need to have a place to appear, so the second listener class will not have to write:

Package SpringTest5;import org. Springframework. Beans. Factory. Annotation. Value;import org. Springframework. Context. Applicationlistener;import org. Springframework. Context. Annotation. Propertysource;import org. Springframework. Stereotype. Component;@Component @propertysource ("Test.properties") public class ListenerTest2 implements applicationlistener<eventtest> {@Value ("${name2}") String Name;public void Onapplicationevent (Eventtest event) {if (event. GetMessage(). Equals(name)) {System. out. println("You need to find"+ Event. GetMessage() +", yes, I am"+ name);} else {System. out                . println("You need to find"+ Event. GetMessage() +", but I 'm not"+ Event. GetMessage() +", I ' AM"+ name);}    }}

After running the main method, the result is as follows:

This example has been packed and uploaded, interested can see, only springTest5 This package is this example, the other package content is on the previous days of blog post to profile and other technical points of the practice, interested can also see.
http://download.csdn.net/detail/tuzongxun/9711034

Use and analysis of custom event events 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.