Spring 如何使用@TransactionalEventListener实现工作单元

Spring 如何使用@TransactionalEventListener实现工作单元,spring,spring-boot,Spring,Spring Boot,我想使用@TransactionalEventListener完成一个工作单元。换句话说,我想注册一个事务回调,它在事务提交之前被触发。我想到的是一个Repository类,它跟踪对聚合根和所有依赖实体所做的更改。当事务即将提交时,它会将整个更改集写入数据库,如下所示 @Component @Transactional class FlightRepository implements Repository{ Flight findById(int id){ // re

我想使用
@TransactionalEventListener
完成一个工作单元。换句话说,我想注册一个事务回调,它在事务提交之前被触发。我想到的是一个Repository类,它跟踪对聚合根和所有依赖实体所做的更改。当事务即将提交时,它会将整个更改集写入数据库,如下所示

@Component
@Transactional
class FlightRepository implements Repository{

    Flight findById(int id){
        // return Flight and start tracking changes
    }

    void add(Flight f){
        // add to list of flights to be created before transaction commit
    }

    void remove(Flight f){
        // add to list of flights to be deleted before transaction commit
    }        

    @TransactionalEventListener(phase = TransactionPhase.BEFORE_COMMIT)
    public void saveChanges(){
       // write all changes to db (adds/removes/updates)
    }
}
我需要确认的是,在提交回调之前,是否仍可以在
事务阶段执行CRUD操作


编辑:将
saveChanges()
访问修饰符从
private
更改为
public
,如注释中所述。没关系。您在提交之前在
回调中所做的操作将在工作单元的同一事务中进行

顺便说一下,为了让
@TransactionalEventListener
工作,您应该将其方法访问修饰符更改为非私有