在程序中,当某些事情发生时(比如用户点击了按钮),系统会发送一个事件,然后监听这个事件的处理器就会被触发,做出相应的反应。
1、定义事件类
public class CustomEvent extends ApplicationEvent {
private String eventData;
public CustomEvent(Object source, String eventData) {
super(source);
this.eventData = eventData;
}
public String getEventData() {
return eventData;
}
}
2、创建事件源
@Service
public class EventProducerService {
private final ApplicationEventPublisher publisher;
@Autowired
public EventProducerService(ApplicationEventPublisher publisher) {
this.publisher = publisher;
}
public void produceEvent() {
String eventData = "This is an example event data";
CustomEvent customEvent = new CustomEvent(this, eventData);
publisher.publishEvent(customEvent);
}
}
3、实现事件监听器
@Component
public class CustomEventListener {
@Async//异步处理
@EventListener
public void handleCustomEvent(CustomEvent event) {
System.out.println("Received custom event with data: " + event.getEventData());
// 这里可以添加处理事件的逻辑
}
}
4、启动应用并触发事件
在Spring Boot应用中,当EventProducerService的produceEvent方法被调用时,它会发布一个CustomEvent,然后CustomEventListener会监听到这个事件并执行handleCustomEvent方法。
@SpringBootApplication
public class Application {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(Application.class, args);
EventProducerService eventProducer = context.getBean(EventProducerService.class);
eventProducer.produceEvent();
}
}
在这个例子中,当我们启动应用并调用produceEvent时,CustomEventListener会打印出接收到的事件数据。请注意,事件监听是异步的,这意味着produceEvent方法调用后,控制权会立即返回,而事件处理会在后台线程中进行。