1

In my Spring Boot/Spring Data app when a user is deleted I want to query and update some other tables.

This tutorial shows how to define an event listener that will be notified when a user is deleted.

@EntityListeners(AuditTrailListener.class)
@Entity
public class User {
    // fields, getters, setters, etc. omitted
}

public class AuditTrailListener {
    private static Log log = LogFactory.getLog(AuditTrailListener.class);
    
    @PostRemove
    private void afterDelete(User user) {
        log.info("[USER AUDIT] add/update/delete complete for user: " + user.getId());
    }    
}

I would like the event listener to itself be a Spring bean, so that I can inject it with Spring Data repository beans that will do the querying and updating of other tables, but as far as I can tell AuditTrailListener is not itself a Spring bean.

I would like the listener to run in the same transaction as the user deletion, such that if a runtime exception is thrown from the listener everything (including the user deletion) will be rolled back.

Is it possible to define a Spring bean persistence event listener which runs in the same transaction as the event it listens to?

Antonio Dragos
  • 1,973
  • 2
  • 29
  • 52

0 Answers0