Spring standard event and custom event observer pattern

spring events

In the official spring documentation, spring events are essentially a standard observer pattern.

Spring events were refactored in Spring 4.2.

system event

system eventdescribe
ContextRefreshedEventThe event published when the application container (ApplicationContext) is initialized or refreshed. For example, the event will be published when the refresh() method of ConfigurableApplicationContext is called.
ContextStartedEventThe event published when the application container is started by calling the start() method of ConfigurableApplicationContext
ContextStoppedEventThe event that is published when the stop() method of the ConfigurableApplicationContext interface is called.
ContextClosedEventThe event that is published when the close() method of the ConfigurableApplicationContext interface is called.
RequestHandledEventMessage event sent after Http request is completed. This event takes effect in the DispatcherServlet of Spring
ServletRequestHandledEventSubclass of RequestHandledEvent, which is used for specific Servlet context information.

Custom event

Declare event

Take the event of adding friends as an example:

public class AddFriendEvent extends ApplicationEvent {
    private String userId;
    private String friendId;
    private String terminal;
    public AddFriendEvent(Object source,String userId,String friendId,String terminal) {
        super(source);
        this.userId = userId;
        this.friendId = friendId;
        this.terminal = terminal;
    }
}

Publish event

The publishEvent () method of ApplicationEventPublisher is used to publish events. In the example of the official document, the object publishing events implements the ApplicationEventPublisherAware interface, in which the ApplicationEventPublisher object can be used to send events directly. However, it is too complex to use. The two methods are as follows:

    @Autowired
    private ApplicationEventPublisher publisher;

spring official example:

public class EmailService implements ApplicationEventPublisherAware {
  private List<String> blockedList;
  private ApplicationEventPublisher publisher;
  public void setBlockedList(List<String> blockedList) {
  this.blockedList = blockedList;
  }
  public void setApplicationEventPublisher(ApplicationEventPublisher publisher) {
  this.publisher = publisher;
  }
  public void sendEmail(String address, String content) {
  if (blockedList.contains(address)) {
  publisher.publishEvent(new BlockedListEvent(this, address, content));
  return;
  }
  }
}

When spring configures beans, the spring container will automatically scan the code of the beans that implement the ApplicationEventPublisherAware interface, and automatically call the setApplicationEventPublisher() method to complete the set injection of ApplicationEventPublisher.

Listening events

Spring provides a variety of ways to implement event listening, which is implemented in spring 5 X mainly implements the applicationlister interface and uses @ EventListener annotation.

Implement the ApplicationListener interface

To receive Spring events, you need to create an object to implement the ApplicationListener interface and register it as a Spring bean. The code example is as follows:

public class BlockedListNotifier implements ApplicationListener<BlockedListEvent> {
  private String notificationAddress;
  public void setNotificationAddress(String notificationAddress) {
  this.notificationAddress = notificationAddress;
  }
  public void onApplicationEvent(BlockedListEvent event) {
  // notify appropriate parties via notificationAddress...
  }
}

To create an event listener, you need to implement a generic (custom Spring event) applicationlister interface. After the event is issued, onApplicationEvent() method will be called, and the event processing logic can be written in this method.

@EventListener annotation.

Listening for messages using annotations

public class BlockedListNotifier {
  private String notificationAddress;
  public void setNotificationAddress(String notificationAddress) {
  this.notificationAddress = notificationAddress;
  }
  @EventListener
  public void processBlockedListEvent(BlockedListEvent event) {
  // notify appropriate parties via notificationAddress...
  }
}

Asynchronous message listening:

Asynchronous message listening can be realized by using @ Async

@EventListener
@Async
public void processBlockedListEvent(BlockedListEvent event) {
  // BlockedListEvent is processed in a separate thread
}

Sequential listening:

Use @ Order(42) to realize sequential message listening

@EventListener
@Order(42)
public void processBlockedListEvent(BlockedListEvent event) {
  // notify appropriate parties via notificationAddress...
}

General message

Declare generic message events

public class EntityCreatedEvent<T> extends ApplicationEvent implements ResolvableTypeProvider {
  public EntityCreatedEvent(T entity) {
  	super(entity);
  }
  @Override
  public ResolvableType getResolvableType() {
  	return ResolvableType.forClassWithGenerics(getClass(),
	ResolvableType.forInstance(getSource()));
  }
}

Listen for general message events

@EventListener
public void onPersonCreated(EntityCreatedEvent<Person> event) {
  // ...
}

Keywords: Java Spring

Added by nunomira on Tue, 21 Dec 2021 08:31:52 +0200