Spring 事件监听机制的使用
文章目录
- 1. 创建自定义事件
- 2. 发布事件
- 3. 监听事件
- 4. 异步事件
1. 创建自定义事件
事件可以是任意对象(Spring 4.2+支持POJO),或继承ApplicationEvent(旧版)。
// 自定义事件(POJO形式,无需继承ApplicationEvent)
public class OrderCreatedEvent {private String orderId;public OrderCreatedEvent(String orderId) {this.orderId = orderId;}public String getOrderId() { return orderId; }
}
2. 发布事件
通过ApplicationEventPublisher发布事件,可在Service中注入该接口。
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;@Service
public class OrderService {private final ApplicationEventPublisher publisher;public OrderService(ApplicationEventPublisher publisher) {this.publisher = publisher;}public void createOrder(String orderId) {// 业务逻辑...// 发布事件publisher.publishEvent(new OrderCreatedEvent(orderId));}
}
3. 监听事件
使用@EventListener注解
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;@Component
public class OrderEventListener {@EventListenerpublic void handleOrderCreated(OrderCreatedEvent event) {System.out.println("订单创建: " + event.getOrderId());// 执行后续操作,如发送邮件、更新库存等}
}
4. 异步事件
可以在启动类上加上@EnableAsync
注解
@SpringBootApplication
@EnableAsync
public class App {public static void main(String[] args) {SpringApplication.run(App.class, args);}
}
在监听到消息执行对应函数的地方加上@Async
注解
@Async@EventListenerpublic void handleOrderCreated(OrderCreatedEvent event) {System.out.println("订单创建: " + event.getOrderId());System.out.println("[同步监听] 线程: " + Thread.currentThread().getName());// 执行后续操作,如发送邮件、更新库存等}