Search code examples
javaspring-bootspring-data-mongodb

Intercept all write calls to MongoDB Spring Boot


I am working with Spring Boot 2.1.5. I am trying to write up a service that intercepts all write calls to the MongoDB. Basically something like the Op log in DBMS where in before any data gets written to DB or even updated or deleted I capture the document that's being updated or created.

Is this even possible? If so how?

It's for the DB calls made from within my application. Because you see let's say you have a large application containing 100 APIs or so, it's tough to actually integrate an OpLog (DB updates, writes, deletes) in all API controllers or services, instead write up an interceptor or aspect that gets triggered before functions of the MongoRepository or MongoTemplate is called.


Solution

  • You can extend of org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener and implement your custom listener.

    Here is the spring docs related.

    The following callback methods are present in AbstractMappingEventListener:

    onBeforeConvert: Called in MongoTemplate insert, insertList, and save operations before the object is converted to a Document by a MongoConverter.

    onBeforeSave: Called in MongoTemplate insert, insertList, and save operations before inserting or saving the Document in the database.

    onAfterSave: Called in MongoTemplate insert, insertList, and save operations after inserting or saving the Document in the database.

    onAfterLoad: Called in MongoTemplate find, findAndRemove, findOne, and getCollection methods after the Document has been retrieved from the database.

    onAfterConvert: Called in MongoTemplate find, findAndRemove, findOne, and getCollection methods after the Document has been retrieved from the database was converted to a POJO.

    If you want to log all operations, you can define a bean of org.springframework.data.mongodb.core.mapping.event.LoggingEventListener.

    @Configuration
    public class MongoConfig {
    
        @Bean
        public LoggingEventListener<Object> listener(){
            return new LoggingEventListener();
        }
    }