Is there any way to execute async method after the execution of spring controller?
Solution 1:
Use the annotation @TransactionalEventListener(phase = TransactionPhase.AFTER_COMPLETION)
to define an event listener that fires after the completion of the transaction in the database:
@Component
public class TransactionEventListener {
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMPLETION)
public void afterCompletion(PayloadApplicationEvent<EventData> event) {
System.out.println("Event data: " + event.getPayload().data);
}
}
Publish the event after saving the data using ApplicationEventPublisher
. Note the method must be annotated with @Transactional
because the transaction is required to fire the event.
@Autowired
private DataRepo dataRepo;
@Autowired
private ApplicationEventPublisher publisher;
@Async
@Transactional
public void storeData() {
...
dataRepo.save(data);
publisher.publishEvent(eventData);
...
}