ApplicationEventPublisher用法-笔记
1.ApplicationEventPublisher简介
org.springframework.context.ApplicationEventPublisher
是 Spring 框架中用于发布自定义事件的核心接口。它允许你在 Spring 应用上下文中触发事件,并由其他组件(监听器)进行响应。
ApplicationEventPublisher相关的核心概念
- 事件(Event):需要发布的自定义事件,继承
ApplicationEvent
。 - 监听器(Listener):通过
@EventListener
注解或实现ApplicationListener
接口来接收事件。 - 发布者(Publisher):通过
ApplicationEventPublisher
接口的publishEvent
方法触发事件。
2.用法介绍
2.1 常见用法步骤
-
定义自定义事件类
继承ApplicationEvent
,并添加必要的属性。 -
创建事件监听器
使用@EventListener
注解或实现ApplicationListener
接口。 -
在需要发布事件的类中注入
ApplicationEventPublisher
通过@Autowired
或构造函数注入,然后调用publishEvent
方法。
2.2 代码示例
step1. 定义自定义事件
import lombok.Getter;
import org.springframework.context.ApplicationEvent;@Getter
public class UserRegisteredEvent extends ApplicationEvent {private final String email;private final String sourceName;public UserRegisteredEvent(String sourceName, String email) {super(sourceName);this.sourceName = sourceName;this.email = email;}}
step2. 创建事件监听器
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;@Component
public class EmailSenderListener {@EventListenerpublic void sendWelcomeEmail(UserRegisteredEvent event) {System.out.println(event.getSourceName() + " 发送欢迎邮件到:" + event.getEmail());}
}
step3. 发布事件的类
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Service;@Service
public class UserService2 {// 通过 @Autowired 方法注入 publisher@Autowiredprivate ApplicationEventPublisher publisher;public void registerUser(String email) {System.out.println("用户注册成功:" + email);// 发布事件publisher.publishEvent(new UserRegisteredEvent("UserService2", email));}
}
step4. 使用
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;@ComponentScan //扫描组件
public class TestMain {public static void main(String[] args) {ApplicationContext context = new AnnotationConfigApplicationContext(TestMain.class);UserService2 userService2 = context.getBean(UserService2.class);userService2.registerUser("user2@example.com");}
}
运行main函数,EmailSenderListener会监听到 UserRegisteredEvent
事件,并输出消息:
2.3 关键点说明
-
依赖注入:
在UserService
中通过构造函数注入ApplicationEventPublisher
,这是 Spring 的推荐方式。publisher对应传入的bean是ApplicationContext
,它是ApplicationEventPublisher的实现。
-
事件监听:
监听器通过@EventListener
注解标记方法,参数类型必须与事件类匹配。 -
事件传递:
ApplicationEventPublisher.publishEvent
方法会将事件广播给所有监听器。 -
异步支持:
如果需要异步处理事件,可以在监听器方法上添加@Async
注解,并启用异步支持(@EnableAsync
)。
2.4 注意事项
- 监听器必须是 Spring 管理的 Bean:通过
@Component
、@Service
等注解标记。 - 事件类型匹配:监听器方法的参数类型必须与事件类完全一致。
- 性能优化:频繁触发的事件可能导致性能问题,需合理设计。
通过这种方式,可以轻松实现在 Spring 应用中解耦组件之间的通信,符合观察者模式的设计理念。