vs direct method call
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.ToString;
@Data
@AllArgsConstructor
@ToString
public class OrderCompletedEvent {
int id;
}
import cz.cizek.edu.springevents.event.OrderCompletedEvent;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class OrderService {
private final ApplicationEventPublisher eventPublisher;
public void completeOrder(int id) {
//here would be the business logic to complete order
System.out.println("Order " + id + " was completed");
eventPublisher.publishEvent(new OrderCompletedEvent(id));
}
}
import cz.cizek.edu.springevents.event.OrderCompletedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
@Component
public class OrderHandler {
@EventListener
public void onOrderCompletedEvent(OrderCompletedEvent orderCompletedEvent) {
// here would be e.g. sending an e-mail
System.out.println("OrderCompletedEvent of order "
+ orderCompletedEvent.getId() + " was processed");
}
}
drawn by dall-e
https://medium.com/@cizek.jy/spring-events-make-your-code-more-flexible-946951ba8e9f