Spring 的 ApplicationEvent and ApplicationListener

什么是ApplicationContext?
它是Spring的核心,Context我们通常解释为上下文环境,但是理解成容器会更好些。
ApplicationContext则是应用的容器。

Spring把Bean(object)放在容器中,需要用就通过get方法取出来。

ApplicationEvent

是个抽象类,里面只有一个构造函数和一个长整型的timestamp。

ApplicationListener

是一个接口,里面只有一个onApplicationEvent方法。

所以自己的类在实现该接口的时候,要实装该方法。

如果在上下文中部署一个实现了ApplicationListener接口的bean,

那么每当在一个ApplicationEvent发布到 ApplicationContext时,
这个bean得到通知。其实这就是标准的Observer设计模式。

首先创建一个Event事件类:

   1. public class EmailListEvent extends ApplicationEvent {  
   2.   
   3.     private static final long serialVersionUID = 1L;  
   4.     public String address;  
   5.     public String text;  
   6.   
   7.     public EmailListEvent(Object source) {  
   8.         super(source);  
   9.     }  
  10.   
  11.     public EmailListEvent(Object source, String address, String text) {  
  12.         super(source);  
  13.         this.address = address;  
  14.         this.text = text;  
  15.     }  
  16.   
  17.     public void print() {  
  18.         System.out.println("Hello,Spring Event!!!");  
  19.     }  
  20. }  


其次创建一个ApplicationListener类:

   1. public class EmailNotifier implements ApplicationListener {  
   2.   
   3.     public void onApplicationEvent(ApplicationEvent evt) {  
   4.         if (evt instanceof EmailListEvent) {  
   5.             EmailListEvent emailEvent = (EmailListEvent) evt;  
   6.             emailEvent.print();  
   7.             System.out.println("the source is:" + emailEvent.getSource());  
   8.             System.out.println("the address is:" + emailEvent.address);  
   9.             System.out.println("the mail's context is :" + emailEvent.text);  
  10.         }  
  11.   
  12.     }  
  13. }  

 


接着将Listener注册到Spring的xml文件中:

<?xml version="1.0" encoding="UTF-8"?>  
 <beans xmlns="http://www.springframework.org/schema/beans"  
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
          xmlns:aop="http://www.springframework.org/schema/aop"  
          xmlns:tx="http://www.springframework.org/schema/tx"  
          xsi:schemaLocation="http://www.springframework.org/schema/beans 
          http://www.springframework.org/schema/beans/spring-beans-2.0.xsd  
          http://www.springframework.org/schema/aop 
          http://www.springframework.org/schema/aop/spring-aop-2.0.xsd  
          http://www.springframework.org/schema/tx 
          http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">  
  
     <bean id="emailListListener" class="spring.event.EmailNotifier"></bean>  
      
</beans>  


最后创建Demo类:

   1. public class ListenerEventDemo {  
   2.   
   3.     /** 
   4.      * @param args 
   5.      */  
   6.     public static void main(String[] args) {  
   7.         ApplicationContext context = new ClassPathXmlApplicationContext(  
   8.                 "SpringEvent.xml");  
   9.         EmailListEvent emailListEvent = new EmailListEvent("hello",  
  10.                 "helloSpring@sina.com", "this is a test eamil content");  
  11.         //在ApplicationContext中发布一个 ApplicationEvent  
  12.         context.publishEvent(emailListEvent);  
  13.     }  
  14.   
  15. }  


测试结果:

# Hello,Spring Event!!!  
# the source is:hello  
# the address is:helloSpring@sina.com  
# the mail's context is :this is a test eamil content  


### Spring ApplicationEvent事件解耦与AOP的区别 #### 应用场景差异 Spring中的`ApplicationEvent`机制主要用于发布/订阅模式下的异步通信,允许组件间松散耦合地传递消息。当某个操作完成时,可以触发一个或多个监听器执行相应的动作[^3]。 相比之下,AOP专注于处理横切关注点——那些影响整个应用程序的功能,比如日志记录、性能监控、安全性验证等。这些方面通常贯穿于系统的各个部分而不局限于单一的操作流程内[^1]。 #### 实现方式的不同 对于`ApplicationEvent`来说,开发者需要定义自定义事件类继承自`ApplicationEvent`基类,并创建对应的Listener接口来接收通知;而在实际运行过程中,则是通过调用`publishEvent()`方法向容器广播指定类型的事件实例给所有注册过的侦听者处理函数[^4]。 另一方面,在采用AOP的方式下,无需改变现有业务代码结构即可引入新的行为特性。这得益于代理机制的支持:无论是JDK动态代理还是CGLIB字节码生成库都能有效地拦截目标对象的方法调用链路,进而实现在前置条件检查、后置返回值转换等方面附加额外逻辑的目的[^2]。 ```java // 定义一个简单的Application Event public class MyCustomEvent extends ApplicationEvent { private String message; public MyCustomEvent(Object source, String msg) { super(source); this.message = msg; } // Getter and Setter... } @Component public class CustomEventListener implements ApplicationListener<MyCustomEvent> { @Override public void onApplicationEvent(MyCustomEvent event) { System.out.println("Received custom event - " + event.getMessage()); } } ``` ```xml <!-- 配置文件中启用AOP支持 --> <aop:aspectj-autoproxy /> <bean id="loggingAspect" class="com.example.LoggingAspect"/> ``` ```java @Aspect @Component public class LoggingAspect { @Before("execution(* com..service.*.*(..))") public void logServiceMethodCall(JoinPoint joinPoint){ System.out.println("Logging service method call:" + joinPoint.getSignature().getName()); } } ```
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值