Spring event notification

1. Concept

Event source : the producer of the event, any EventObject must have an event source.

Event listener registry : The event listener of a component or framework cannot float in the air, but must depend on it. In other words, the component or framework must provide a place to store event listeners, which is the event listener registry. An event listener registered in a component or framework is actually saved in the event listener registry. When the event source in the component and the framework generates an event, it will notify these listeners in the event listener registry.

Event broadcaster : It is the bridge between the event and the event listener, and is responsible for notifying the event to the event listener.

Two, code example

Event source

public class SpringTestEvent  extends ApplicationEvent {
    private String message;
    public SpringTestEvent(Object source,String message) {
        super(source);
        System.out.println("事件源=="+message);
        this.message = message;
    }
    public String getMessage() {
        return message;
    }
}

Event broadcaster: call sendMsg() during operation, it can be executed.

@Component
public class SpringTestBean  implements ApplicationContextAware {

    @Autowired
    ApplicationContext applicationContext;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
    public void sendMsg(){
        String msg ="455668666";
        System.out.println("======"+msg);
        applicationContext.publishEvent(new SpringTestEvent(this ,msg));
    }
}

Event listener registry: get the corresponding listener for operation

@Component
public class SpringTestListener implements ApplicationListener<SpringTestEvent> {

    @Override
    public void onApplicationEvent(SpringTestEvent springTestEvent) {
        System.out.println("事件监听者:===="+springTestEvent.getMessage());
    }
}

Three, code logic

1. The project loads refresh() to initialize the bean container, initialize the application context event broadcaster, register the event listener, complete the refresh and publish the container refresh event.

2. Initialize the event source new SpringTestEvent (applicationContext, msg)

3. Use the method publishEvent() of ApplicationContext to broadcast events.

4. Get the ApplicationEventMulticaster event broadcaster in AbstractApplicationContext

5. Obtain a custom SpringTestListener according to the event listener registry traversal, and listen to the event source

 

Core: initialization of the bean container, ApplicationContext application context processing.

Guess you like

Origin blog.csdn.net/baidu_28068985/article/details/104819190