Spring中ApplicationListener的使用

10次阅读

共计 1804 个字符,预计需要花费 5 分钟才能阅读完成。

背景

ApplicationListener 是 Spring 事件机制的一部分,与抽象类 ApplicationEvent 类配合来完成 ApplicationContext 的事件机制。

如果容器中存在 ApplicationListener 的 Bean,当 ApplicationContext 调用 publishEvent 方法时,对应的 Bean 会被触发。这一过程是典型的观察者模式的实现。

ApplicationListener 源码

@FunctionalInterface
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {

    /**
     * Handle an application event.
     * @param event the event to respond to
     */
    void onApplicationEvent(E event);

}

ContextRefreshedEvent 事件的监听

以 Spring 的内置事件 ContextRefreshedEvent 为例,当 ApplicationContext 被初始化或刷新时,会触发 ContextRefreshedEvent 事件,下面我们就实现一个 ApplicationListener 来监听此事件的发生。

@Component // 需对该类进行 Bean 的实例化
public class LearnListener implements ApplicationListener<ContextRefreshedEvent> {
   @Override
   public void onApplicationEvent(ContextRefreshedEvent event) {
      // 打印容器中出事 Bean 的数量
      System.out.println("监听器获得容器中初始化 Bean 数量:" + event.getApplicationContext().getBeanDefinitionCount());
   }
}

如上,便完成了一个事件监听类的实现和实例化。

自定义事件及监听

首先自定义事件:NotifyEvent。

public class NotifyEvent extends ApplicationEvent {


    private String email;

    private String content;

    public NotifyEvent(Object source) {super(source);
    }

    public NotifyEvent(Object source, String email, String content) {super(source);
        this.email = email;
        this.content = content;
    }
    // 省略 getter/setter 方法
}

定义监听器 NotifyListener:

@Component
public class NotifyListener implements ApplicationListener<NotifyEvent> {

    @Override
    public void onApplicationEvent(NotifyEvent event) {System.out.println("邮件地址:" + event.getEmail());
        System.out.println("邮件内容:" + event.getContent());
    }
}

监听器通过 @Component 注解进行实例化,并在 onApplicationEvent 中打印相关信息。

单元测试类:

@RunWith(SpringRunner.class)
@SpringBootTest
public class ListenerTest {

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Test
    public void testListener() {NotifyEvent event = new NotifyEvent("object", "abc@qq.com", "This is the content");

        webApplicationContext.publishEvent(event);
    }
}

执行单元测试,会发现事件发布之后,监听器方法被调用,日志被打印出来。

原文链接:https://www.choupangxia.com/2…

正文完
 0