Event handling in spring (9)

The core of spring is ApplicationContext, which manages the full life cycle of beans. ApplicationContext publishes certain types of events when loading beans. For example, contextstartedevent starts when the context starts and publishes contextstoppedevent when the context stops publishing.

Event handling in ApplicationContext is provided through applicationevent class and applicationlistener interface. Therefore, if the bean implements applicationlistener, it will be notified every time applicationevent is published to ApplicationContext.

Spring's event handling is single threaded, so if an event is published, the process will be blocked and will not continue unless all recipients receive the message. Therefore, if you want to use event handling, you should be careful when designing your application.

Listen for context events

To listen for context events, the bean should implement the applicationlistener interface, which has only one onapplicationevent () method. Therefore, let's write an example to see how events propagate and how to make code perform the required tasks according to a specific event.

Example:

(1) Write HelloWorld java

(2) Write cstarteventhandler java

(3) Write cstopeventhandler java

(4) Write mainapp java

(5) Write beans xml

(6) Run mainapp The result of the main method in Java is as follows:

@H_ 56_ 301@

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>