Today idle nothing through to the domestic pig source of micro encapsulation service is good, see the wraps a utility class USES ApplicationEventPublisher Spring inside is the protagonist of this article today, comes from to the class don’t know is why, in baidu recorded: by the way, after the may I’ll be able to use it

  • ApplicationEventPublisher is publishEvent asynchronous quick implementation
  • Using ApplicationEventPublisher publishEvent to publish events

This feels a little bit like MQ at first, where MQ is sending messages, receiving messages, and this is pushing events, listening for events. Here I simulate the insertion of a user and push the user’s information as an event and finally print it

Without further ado, let’s get right to the code

  1. Create the user entity class UserDTO
/ * * *@authorPeng * o@date2021/9/3 plague * /
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class UserDTO {
    private String name;
    private String sex;
}
Copy the code
  1. Create a service, not a Service, that can be injected into the Spring container and run in my test class
/ * * *@authorPeng * o@dateLet's say this class is a service class. We need to simulate a method to save the user and then send events and listen */
@Component
@RequiredArgsConstructor
public class ApplicationEventSender {

    private final ApplicationEventPublisher publisher;

    public void saveUser(UserDTO dto) {
		// Push eventspublisher.publishEvent(dto); }}Copy the code
  1. I’m going to use the condition attribute (condition), and the expression in the condition attribute is the Spring SPEL expression
/ * * *@authorPeng * o@date2021/9/3 * / to him
@Component
public class EventListenerDemo {

    @EventListener(condition = "#user.name! =null")
    public void watch(UserDTO user) {
		// If the user name is null, none of the following will be executedSystem.out.println(user.getName()); System.out.println(user.getSex()); }}Copy the code
  1. test
    @Autowired
    private ApplicationEventSender sender;

    @Test
    public void testSpringWatch(a) {
        sender.saveUser(UserDTO.builder()
                .name("Ah Peng has been cleaning since he was a child.")
                .sex("Male")
                .build());
    }
Copy the code