Support for Observer design patterns in Spring.

xiaoxiao2021-03-06  36

I believe that if everyone has done the development of Win32, it must be familiar with user-defined user events. The time processing of ApplicationContext in Spring is implemented through the ApplicationEvent class and the ApplicationListener interface. When you execute ApplicationListener in your beans, your bean gets Notified in each time an ApplicationEvent is published. This depends on the standard, OBSERVER design mode. Spring provides three standard Events: ContextRefreShedEvent, when ApplicationContext is initialized or refreshed, this event is excited. Initialization means all loaded, Singletons is pre-instantiated, and ApplicationContext can be used. ContextCloseDevent stimulates this event when ApplicationContext is off. That is, Singletons is released. RequestHandledEvent A web-based Event tells all the Beans an HTTP request being served. (The above translation from Spring Reference 3.10.2) provides an example in Spring, I tried it, or more feeling comfortable. ApplicationContext definition:

Java code:

black@list.org white@list.org john@doe.org Spam@list.org

The actual bean code is as follows:

Java code:

public class EmailBean implements ApplicationContextAware {/ ** the blacklist * / private List blackList; public void setBlackList (List blackList) {this.blackList = blackList;} public void setApplicationContext (ApplicationContext ctx) {this.ctx = ctx;} public void sendEmail (String address, String text) {if (blackList.contains (address)) {BlackListEvent evt = new BlackListEvent (address, text); ctx.publishEvent (evt); return;} // send email}} public class BlackListNotifier implement ApplicationListener {/ ** notification address * / private String notificationAddress; public void setNotificationAddress (String notificationAddress) {this.notificationAddress = notificationAddress;} public void onApplicationEvent (ApplicationEvent evt) {if (evt instanceof BlackListEvent) {// notify appropriate person and not the text Give the code of the BlackListevent, I am implemented as follows:

Java code:

Public Class Blacklistevent Extends ApplicationEvent {Public BlackListevent (Object O) {Super (O);}}

You can expand new classes by executing the ApplicationListener interface. Experience the convenience of Spring brings you. Also, I am looking at Spring, I found a new class (not mentioned in Spring Reference), it is ConfigurableApplicationContext, which extends the ApplicationContext class and provides a Close () and refresh () method. That is to say, you can trigger the ContextCloseDevent event and the ContextRefreeshedEvent event, but I found that when the close () method is called, ApplicationContext is not closed, but the behavior is updated. It's so strange, I haven't figured out how it is. Oh, I hope that the senior can give me a point one or two!

转载请注明原文地址:https://www.9cbs.com/read-66498.html

New Post(0)