Event listener usage in spring

 

Go directly to the code to see the usage:

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

/**
 * spring startup listener class
 * @author zhaoxing
 * @version Id: ListenerBusiness.java, v 0.1 2017/4/27 15:13 zhaoxing Exp $$
 */
@ Slf4j
@Component
public class ListenerBusiness implements ApplicationListener<ContextRefreshedEvent> {


    @Override
    public void onApplicationEvent(ContextRefreshedEvent evt) {
        /**
         * In a web project (spring mvc), there will be two containers in the system, one is the root application context,
         * The other is our own projectName-servlet context (as a subcontainer of the root application context).
         * In this case, the onApplicationEvent method will be executed twice. To avoid this problem,
         * We can call the logic code only after the initialization of the root application context is completed, and the initialization of other containers is completed, then do nothing
         */
        if (evt.getApplicationContext().getParent() == null) {
            doBusiness();
        }
    }

    public void doBusiness(){
        log.info("Start the listener class to start...");
        // do other business
    }
}

 

Among them, ApplicationListener< extends  ApplicationEvent>   is the listener interface used to implement in the spring framework, and the event that the listener listens to is specified in the generic type. There is only one interface method in the interface, which is used for the interface implementation class to execute the business logic processing method after listening to the corresponding event.

 

The corresponding source code is as follows:

/**
 * An event listener implemented in the spring framework, based on the standard java.util.EventListener interface (observer design pattern)
 *
 * @param <E> The type of event to monitor, which is a subclass of ApplicationEvent
 */
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {

    /**
     * The business processing method to be executed after listening to a specific event.
     * @param event the event to respond to
     */
    void onApplicationEvent(E event);

}

/**
 * This event is fired when the application starts or refreshes (gets initialized or refreshed).
 */
public class ContextRefreshedEvent extends ApplicationContextEvent {

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327003705&siteId=291194637