Spring - 事件(ApplicationListener和ApplicationEvent)

ApplicationListener

ApplicationListener监听系统发布的事件。自定义Listener类,实现ApplicationListener接口,同时需要传一个泛型,我们这里就选择事件的父类:ApplicationEvent,再将我们定义的ApplicationListener注入到Spring的IOC容器中(用@Component注解)

@Component
public class MyApplicationLitener implements ApplicationListener<ApplicationEvent> {
    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        System.out.println("收到事件:" + event.toString());
    }
}

编写配置文件(主要一个@ComponentScan注解,扫描我们自定义的事件监听器,然后加入到Spring的IOC容器中)

@ComponentScan("com.booyue.tlh.ext")
@Configuration//告诉Spring这是一个配置类
public class ExtConfig {
}

测试代码(创建容器和关闭容器),能收到容器的创建和关闭事

    @Test
    public void testAnnotation15() {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ExtConfig.class);
        context.close();
    }

//打印信息
收到事件:org.springframework.context.event.ContextRefreshedEvent[source=org.springframework.context.annotation.AnnotationConfigApplicationContext@51b7e5df, started on Tue Jun 22 20:54:56 CST 2021]
收到事件:org.springframework.context.event.ContextClosedEvent[source=org.springframework.context.annotation.AnnotationConfigApplicationContext@51b7e5df, started on Tue Jun 22 20:54:56 CST 2021]

自定义事件

实现ApplicationEvent接口

public class MyApplicationEvent extends ApplicationEvent {
    /**
     * Create a new {@code ApplicationEvent}.
     *
     * @param source the object on which the event initially occurred or with
     *               which the event is associated (never {@code null})
     */
    public MyApplicationEvent(Object source) {
        super(source);
    }
}

使用ApplicationContext发布事件,自定义的事件监听器就能收到我们自定义的事件

    @Test
    public void testAnnotation15() {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ExtConfig.class);
        context.publishEvent(new MyApplicationEvent(new String("自定义事件!!!")));
        context.close();
    }

//打印信息
收到事件:org.springframework.context.event.ContextRefreshedEvent[source=org.springframework.context.annotation.AnnotationConfigApplicationContext@51b7e5df, started on Tue Jun 22 21:08:28 CST 2021]
收到事件:com.booyue.tlh.ext.MyApplicationEvent[source=自定义事件!!!]
收到事件:org.springframework.context.event.ContextClosedEvent[source=org.springframework.context.annotation.AnnotationConfigApplicationContext@51b7e5df, started on Tue Jun 22 21:08:28 CST 2021]

@EventListener

通过@EventListener注解也能让某一个实例方法监听指定事件(可以指定监听事件类型)

@Service
public class EventService {

    @EventListener(classes = {ApplicationEvent.class})
    public void listener(ApplicationEvent event) {
        System.out.println("EventService ->"+event);
    }
}

事件发布流程

获取到事件派发器

获取到事件监听器

发布事件

猜你喜欢

转载自blog.csdn.net/qq_27062249/article/details/118116815