Spring 事件监听机制的使用

发布于:2025-05-15 ⋅ 阅读:(15) ⋅ 点赞:(0)

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 {
    
    @EventListener
    public 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
    @EventListener
    public void handleOrderCreated(OrderCreatedEvent event) {
        System.out.println("订单创建: " + event.getOrderId());
        System.out.println("[同步监听] 线程: " + Thread.currentThread().getName());
        // 执行后续操作,如发送邮件、更新库存等
    }

网站公告

今日签到

点亮在社区的每一天
去签到