Interceptor for MongoDB in Java

4k Views Asked by At

I'm new to Spring and MongoDB. I'm trying to audit the CRUD operations on MongoDB. I've found many plugins that audit the changes on MongoDB level, but I'm looking for something like an interceptor or hook (for example, EmptyInterceptor for hibernate) which works on Java level.

I'm using GMongo on Java to operate on MongoDB. What is something which can help me in this matter?

2

There are 2 best solutions below

4
On

I think you can try CommandListener. You just need new a object that implement the interface and add it to MongoClientOptions, then use the MongoClientOptions create a MongoClient. like that:

MongoCommandListener listener = new MongoCommandListener();

MongoClientOptions options =
                        MongoClientOptions.builder().addCommandListener(listener).build();

return new MongoClient(new ServerAddress(host,port), options);
4
On

spring-data-mongodb provides AbstractMongoEventListener for exactly these purposes.
Do read the complete Lifecycle events here.

All you have got to do is write a class (make sure Spring scans it, using @Configuration or componentscan) which extends AbstractMongoEventListener and implement various abstract methods provided by AbstractMongoEventListener and write your audit logic inside these methods.

Take a look at LoggingEventListener under org.springframework.data.mongodb.core.mapping.event in your spring-data-mongodb jar.