Spring event (1) - built-in event


Spring series of tutorials


Spring events is a ApplicationEventsubclass of the class by the realization of ApplicationEventPublisherAwarethe interface sending a class that implements the ApplicationListenerclass monitor interface.

ApplicationContext event

Spring is already defines a set of built-in events that the ApplicationContextissue of the container.

For example, ContextStartedEventin ApplicationContextsending the start, ContextStoppedEventthe ApplicationContextsending stop.

Achieve ApplicationListenerclass can listen for events.

Spring events are synchronized (single-threaded), will be blocked.

ApplicationContext monitor events

To listen for ApplicationContextthe event, the listener class should implement ApplicationListenerthe interface and override the onApplicationEvent()method.

ContextStartEventHandler.java

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextStartedEvent;

public class ContextStartEventHandler implements ApplicationListener<ContextStartedEvent>{

    @Override
    public void onApplicationEvent(ContextStartedEvent event) {
        System.out.println("ApplicationContext 启动... ");
    }
}

Test.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
  public static void main(String[] args) {
    // ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    // fire the start event.
    // ((ConfigurableApplicationContext) context).start();
    
    ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    // fire the start event.
    context.start();
    
    // ...
    
  }
}

In the XML configuration file, the class is declared as Bean, Spring containers to load the Bean, and transmits its events.

<bean id="contextStartEventHandler" class="ContextStartEventHandler"></bean>

Guess you like

Origin www.cnblogs.com/jinbuqi/p/10987724.html