With the help of Spring, the event monitoring mechanism can be implemented very simply. This article briefly introduces the following two postures for interface and annotation monitoring

[SpringBoot Basic Series] Two consumption postures of the event mechanism

<!-- more -->

I. Project environment

This project is developed with the help of SpringBoot 2.2.1.RELEASE + maven 3.5.3 + IDEA

In order to verify the subsequent release event, set up a web service

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

II. Event Mechanism

1. Event Object

In Spring, all events need to be inherited from ApplicationEvent , a basic MsgEvent as follows

public class MsgEvent extends ApplicationEvent {
    private String msg;

    /**
     * Create a new {@code ApplicationEvent}.
     *
     * @param source the object on which the event initially occurred or with
     *               which the event is associated (never {@code null})
     */
    public MsgEvent(Object source, String msg) {
        super(source);
        this.msg = msg;
    }

    @Override
    public String toString() {
        return "MsgEvent{" +
                "msg='" + msg + '\'' +
                '}';
    }
}

2. Interface consumption

There are two ways to consume events. The interface declaration is mainly to implement the ApplicationListener interface; note that the listener needs to be declared as a Spring bean object

@Service
public class MsgEventListener implements ApplicationListener<MsgEvent> {
    @Override
    public void onApplicationEvent(MsgEvent event) {
        System.out.println("receive msg event: " + event);
    }
}

3. Consumption in annotated way

To implement the interface, you need to create a new implementation class. The simpler method is to add an annotation @EventListener

@EventListener(MsgEvent.class)
public void consumer(MsgEvent msgEvent) {
    System.out.println("receive msg by @anno: " + msgEvent);
}

This annotation supports matching according to the Event parameter type, that is, in the above example, it does not matter if @EventListener

4. Post an event

The preceding is consumption events. The premise of consumption is that there are events. In Spring, publishing events mainly needs to be achieved ApplicationContext

@Service
public class MsgPublisher implements ApplicationContextAware {
    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public void publish(String msg) {
        applicationContext.publishEvent(new MsgEvent(this, msg));
    }
}

5. Testing

A simple test demo

@RestController
public class IndexController {
    @Autowired
    private MsgPublisher msgPublisher;

    @GetMapping(path = "pub")
    public String publish(String msg) {
        msgPublisher.publish(msg);
        return "ok";
    }
}

Visit: curl http://localhost:8082/pub?msg=Yihuihuiblog

Output log:

receive msg by @anno: MsgEvent{msg='一灰灰blog'}
receive msg event: MsgEvent{msg='一灰灰blog'}

The above test can be successful in both consumption methods. However, a case was found during the actual test. The annotation consumption method does not take effect. The test posture is as follows

@SpringBootApplication
public class Application {

    public Application(MsgPublisher msgPublisher) {
        msgPublisher.publish("一灰灰blog");
    }
    public static void main(String[] args) {
        SpringApplication.run(Application.class);
    }

}

Directly publish the event in the constructor of the startup class, and found that the interface method can receive the event, but the annotation method does not take effect, why?

There is a similar question https://stackoverflow.com/questions/38487474/springboot-eventlistener-dont-receive-events , here is a point of view

  • Publish the message earlier than the event consumption registration

Is this the reason? Waiting for the next source code analysis

II. Other

0. Project

1. A Grey Blog

It is not as good as the letter. The above content is purely a family statement. Due to limited personal ability, it is inevitable that there will be omissions and errors. If you find a bug or have better suggestions, you are welcome to criticize and correct me, and I am grateful.

The following is a gray personal blog, which records all the blog posts in study and work. Welcome everyone to visit

一灰灰blog


小灰灰Blog
251 声望46 粉丝