一、简介
spring框架是java开发中常用的,通常我们需要在spring的某些事件发生时,做某些操作。
在此介绍spring的内置事件,以父抽象类ApplicationContextEvent下的四个子事件类为主。
类图如下:
二、事件类
1、ApplicationContextEvent
是spring内置事件的父抽象类,构造方法传入spring的context容器,同时也有获取spring的context容器的方法。
源码如下:
/** * Base class for events raised for an { @code ApplicationContext}. * * @author Juergen Hoeller * @since 2.5 */ @SuppressWarnings("serial") public abstract class ApplicationContextEvent extends ApplicationEvent { /** * Create a new ContextStartedEvent. * @param source the { @code ApplicationContext} that the event is raised for * (must not be { @code null}) */ public ApplicationContextEvent(ApplicationContext source) { super(source); } /** * Get the { @code ApplicationContext} that the event was raised for. */ public final ApplicationContext getApplicationContext() { return (ApplicationContext) getSource(); } }2、ContextRefreshedEvent
当spring容器初始化或刷新时,会触发此事件。此事件在开发中常用,用于在spring容器启动时,导入自定义的bean实例到spring容器中。
源码如下:
/** * Event raised when an { @code ApplicationContext} gets initialized or refreshed. * * @author Juergen Hoeller * @since