Spring series of tutorials
- Spring Framework Introduction
- Spring Framework module
- Spring development environment to build (Eclipse)
- Create a simple Spring application
- Spring Inversion of Control container (Inversion of Control - IOC)
- Appreciated dependency injection (DI - Dependency Injection)
- Bean XML configuration (1) - through XML configuration loaded Bean
- Bean XML configuration (2) - Bean scope and lifecycle callback method configuration
- Bean XML configuration (3) - configuration dependency injection
- Bean XML configuration (4) - Automatic Assembly
- Bean annotation (Annotation) Configuration (1) - Load Bean via annotations
- Bean annotation (Annotation) Configuration (2) - Bean scope and lifecycle callback method configuration
- Bean Annotations (Annotation) configuration (3) - configuration dependency injection
- Bean Java Configuration
- Spring Aspect Oriented Programming (AOP)
- Spring event (1) - built-in event
- Spring event (2) - Custom Event
Spring events is a ApplicationEvent
subclass of the class by the realization of ApplicationEventPublisherAware
the interface sending a class that implements the ApplicationListener
class monitor interface.
ApplicationContext event
Spring is already defines a set of built-in events that the ApplicationContext
issue of the container.
For example, ContextStartedEvent
in ApplicationContext
sending the start, ContextStoppedEvent
the ApplicationContext
sending stop.
Achieve ApplicationListener
class can listen for events.
Spring events are synchronized (single-threaded), will be blocked.
ApplicationContext monitor events
To listen for ApplicationContext
the event, the listener class should implement ApplicationListener
the 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>