|
| 1 | +package org.baeldung.springevents.synchronous; |
| 2 | + |
| 3 | +import org.springframework.context.event.ContextStartedEvent; |
| 4 | +import org.springframework.context.event.EventListener; |
| 5 | +import org.springframework.stereotype.Component; |
| 6 | +import org.springframework.transaction.event.TransactionPhase; |
| 7 | +import org.springframework.transaction.event.TransactionalEventListener; |
| 8 | + |
| 9 | +@Component |
| 10 | +public class AnnotationDrivenEventListener { |
| 11 | + |
| 12 | + // for tests |
| 13 | + private boolean hitContextStartedHandler = false; |
| 14 | + private boolean hitSuccessfulEventHandler = false; |
| 15 | + private boolean hitCustomEventHandler = false; |
| 16 | + |
| 17 | + @EventListener |
| 18 | + public void handleContextStart(final ContextStartedEvent cse) { |
| 19 | + System.out.println("Handling context started event."); |
| 20 | + hitContextStartedHandler = true; |
| 21 | + } |
| 22 | + |
| 23 | + @EventListener(condition = "#event.success") |
| 24 | + public void handleSuccessful(final GenericSpringEvent<String> event) { |
| 25 | + System.out.println("Handling generic event (conditional): " + event.getWhat()); |
| 26 | + hitSuccessfulEventHandler = true; |
| 27 | + } |
| 28 | + |
| 29 | + @TransactionalEventListener(phase = TransactionPhase.BEFORE_COMMIT) |
| 30 | + public void handleCustom(final CustomSpringEvent event) { |
| 31 | + System.out.println("Handling event inside a transaction BEFORE COMMIT."); |
| 32 | + hitCustomEventHandler = true; |
| 33 | + } |
| 34 | + |
| 35 | + boolean isHitContextStartedHandler() { |
| 36 | + return hitContextStartedHandler; |
| 37 | + } |
| 38 | + |
| 39 | + boolean isHitSuccessfulEventHandler() { |
| 40 | + return hitSuccessfulEventHandler; |
| 41 | + } |
| 42 | + |
| 43 | + boolean isHitCustomEventHandler() { |
| 44 | + return hitCustomEventHandler; |
| 45 | + } |
| 46 | +} |
0 commit comments