Spring events
vs direct method call
Co ?
- implementace publish - subscribe
Proč
- loose couple design
- podporuje OCP
- výrazně jednodušší testing
Jak
- event - POJO, nese data
- publisher - komponenta pro emitaci eventů
- listener - zpracování eventu
Event
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.ToString;
@Data
@AllArgsConstructor
@ToString
public class OrderCompletedEvent {
int id;
}
Publisher
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));
}
}
- Spring bean ApplicationEventPublisher
Listener
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");
}
}
- metoda anotovaná @EventListener a přijímající event
Show time
Transactional bound events
- umožní pozdržet zpracování eventu na výsledek transakce
- změna @EventListener na @TransactionalEventListener
- podpora 4 fází transakce
Fix time
Async events
- Synchronní, defaultní chování
Async events
- @EnableAsync - enable asynchronního chování
- @Async - označení listeneru jako asynchronní
Fix time
Bonus
- event chain
- event filter
drawn by dall-e
https://medium.com/@cizek.jy/spring-events-make-your-code-more-flexible-946951ba8e9f
Spring events
By Jiří Čížek
Spring events
- 72