Event implementation of Spring

Keywords: Spring

The event mechanism is divided into three steps:
1. Custom events
2. Listening events
3. Release event
Before spring 4.2:

1. Custom events
Note: custom events need to inherit ApplicationEvent

import org.springframework.context.ApplicationEvent;
public class BlackListEvent extends ApplicationEvent {
    //Custom events
    public BlackListEvent(Object source) {
        super(source);
    }
}

2. Listening events

Note: listening needs to inherit ApplicationListener generics, which refer to custom events. The monitor should be handed over to Spring for management and instantiation;

import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
public class BlackListNotifier implements ApplicationListener<BlackListEvent> {
    @Override
    public void onApplicationEvent(BlackListEvent blackListEvent) {
        //Event processing business can be written here
    }
}

3. Release event

/*Inject where the event needs to be used: ApplicationEventPublisher calls the publishEvent() method; to publish a custom event, instantiate BlackListEvent blackListEvent =new BlackListEvent(userAuthRequestDTO.getUsername());*/

@Autowired
ApplicationEventPublisher applicationEventPublisher;

public UserAuthResponseDTO auth(UserAuthRequestDTO userAuthRequestDTO) throws Exception {
        BlackListEvent blackListEvent =new BlackListEvent(userAuthRequestDTO.getUsername());
        applicationEventPublisher.publishEvent(blackListEvent);
    }

After spring 4.2:
1. Custom events
Note: custom events need to inherit ApplicationEvent

import org.springframework.context.ApplicationEvent;
public class BlackListEvent extends ApplicationEvent {
    //Custom events
    public BlackListEvent(Object source) {
        super(source);
    }
}

2. Listening events

Note: listening does not need to inherit ApplicationListener, use annotation @ EventListener and reflect custom events
Events are synchronous by default. You need to add @ Async asynchronously

import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
public class BlackListNotifier {
    @EventListener(BlackListEvent.class)
    //@Async
    public void onApplicationEvent(BlackListEvent blackListEvent) {
        //Event processing business can be written here
    }
}

3. Release event

/*Inject where the event needs to be used: ApplicationEventPublisher calls the publishEvent() method; to publish a custom event, instantiate BlackListEvent blackListEvent =new BlackListEvent(userAuthRequestDTO.getUsername());*/

@Autowired
ApplicationEventPublisher applicationEventPublisher;

public UserAuthResponseDTO auth(UserAuthRequestDTO userAuthRequestDTO) throws Exception {
        BlackListEvent blackListEvent =new BlackListEvent(userAuthRequestDTO.getUsername());
        applicationEventPublisher.publishEvent(blackListEvent);
    }

Posted by crees on Wed, 01 Apr 2020 18:31:13 -0700