Spring 系列教程


Spring中的事件是一个ApplicationEvent类的子类,由实现ApplicationEventPublisherAware接口的类发送,实现ApplicationListener接口的类监听。

ApplicationContext 事件

Spring中已经定义了一组内置事件,这些事件由ApplicationContext容器发出。

例如,ContextStartedEventApplicationContext启动时发送,ContextStoppedEventApplicationContext停止时发送。

实现ApplicationListener的类可以监听事件。

Spring的事件是同步的(单线程的),会被阻塞。

监听ApplicationContext事件

要监听ApplicationContext事件,监听类应该实现ApplicationListener接口并重写onApplicationEvent()方法。

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();
    
    // ...
    
  }
}

在XML配置文件中,将该类为声明为Bean,以便Spring容器加载该Bean,并向其传送事件。

<bean ></bean>

相关文章:

  • 2022-01-23
  • 2022-01-27
  • 2022-12-23
  • 2021-09-17
  • 2022-12-23
  • 2021-08-13
  • 2021-09-15
  • 2022-12-23
猜你喜欢
  • 2021-12-27
  • 2021-12-10
  • 2021-11-07
  • 2021-12-29
  • 2021-10-17
相关资源
相似解决方案