2

I have a (simplified below) RestController invoking a CrudRepository.

@RestController
@RequestMapping({"/carApi"})
public class RestService {
    @Autowired
    private StorageService storageService;

    @PostMapping
    public RightTriangle create(@RequestBody DegregatedCar degregatedCar) {
        // Some logic
        Car car = convert(degregatedCar);
        return storageService.save(car);
    }
}

public interface StorageService extends CrudRepository<Car, Long> {
}

I'd like to do some additional stuff after the entity (car in this case) is saved.

I tried using @RepositoryEventHandler and AbstractRepositoryEventListener but, as stated here, these only work when invoked by the CrudRepository exposed REST. Meaning, not working when invoked programmatically.

Any idea how to listen to repository events, regardless of how they are invoked?

AlikElzin-kilaka
  • 34,335
  • 35
  • 194
  • 277

2 Answers2

1
  1. If you are using Mongo(spring-data-mongodb), you can use Mongo Lifecycle Events. For example

    @Component
    public class MongoListener extends AbstractMongoEventListener<YourEntity>
    {
    
       @Override
       public void onAfterSave(AfterSaveEvent<YourEntity> event) {
          // Your logic here.       
        }
      }
    //There are many other methods in AbstractMongoEventListener like onBeforeSave ......
    }
    
  2. If you are using any relational databases with spring-data-jpa, you can use JPA Lifecycle Events like

    @PrePersist void onPrePersist() {}
    @PostPersist void onPostPersist() {}
    .......
    

You can use this in your Entity class

pvpkiran
  • 25,582
  • 8
  • 87
  • 134
1

Solved it using AOP. Example:

@Aspect
@Component
public class SystemLoggerService {
    @Around("execution(* com.whatever.StorageService.save(..))")
    public void around(ProceedingJoinPoint joinPoint) throws Throwable {
        // TODO: Handle saving multiple save methods.
        // TODO: Log after transaction is finished.
        Car car = (Car) joinPoint.getArgs()[0];
        boolean isCreated = car.id == null;
        joinPoint.proceed();
        if (isCreated) {
            LOGGER.info("Car created: " + car);
        } else {
            LOGGER.info("Car saved: " + car);
        }
    }
}
AlikElzin-kilaka
  • 34,335
  • 35
  • 194
  • 277