Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auditing with spring-data-mongodb

I am trying to enable auto audit fields with spring data mongodb as explained here. Below is my configuration class

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.abc")
@EnableMongoRepositories(basePackages = "com.abc.xyz.repository")
@EnableMongoAuditing
public class ApplicationConfiguration {

    @Bean
    public MongoDbFactory mongoDbFactory() throws Exception {
        ServerAddress serverAddress = new ServerAddress("127.0.0.1", 27017);
        MongoCredential mongoCredential = MongoCredential.createCredential("user", "test", "abc123".toCharArray());
        MongoClient mongoClient = new MongoClient(serverAddress, Arrays.asList(mongoCredential));
        return new SimpleMongoDbFactory(mongoClient, "test");
    }

    @Bean
    public MongoTemplate mongoTemplate() throws Exception {
        return new MongoTemplate(mongoDbFactory());
    }
}

But when I add @EnableMongoAuditing, I am getting the below error on starting the server.

Caused by: java.lang.RuntimeException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoAuditingHandler': Cannot create inner bean '(inner bean)#6dca0c34' of type [org.springframework.data.mongodb.config.MongoAuditingRegistrar$MongoMappingContextLookup] while setting constructor argument; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name '(inner bean)#6dca0c34': Unsatisfied dependency expressed through constructor parameter 0: No qualifying bean of type [org.springframework.data.mongodb.core.convert.MappingMongoConverter] found for dependency [org.springframework.data.mongodb.core.convert.MappingMongoConverter]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.data.mongodb.core.convert.MappingMongoConverter] found for dependency [org.springframework.data.mongodb.core.convert.MappingMongoConverter]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
    at io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:236)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentService.startContext(UndertowDeploymentService.java:100)
    at org.wildfly.extension.undertow.deployment.UndertowDeploymentService$1.run(UndertowDeploymentService.java:82)
like image 594
rohit Avatar asked Jan 08 '17 06:01

rohit


People also ask

How do I audit in MongoDB?

The auditing facility can write audit events to the console, the syslog, a JSON file, or a BSON file. To enable auditing in MongoDB Enterprise, set an audit output destination with --auditDestination . For details, see Configure Auditing. For information on the audit log messages, see System Event Audit Messages.

Can I use spring data JPA with MongoDB?

Yes, DataNucleus JPA allows it, as well as to many other databases. You make compromises by using the JPA API for other types of datastores, but it makes it easy to investigate them.

What is the difference between MongoOperations and MongoTemplate?

MongoTemplate provides a simple way for you to save, update, and delete your domain objects and map those objects to documents stored in MongoDB. You can save, update and delete the object as shown below. MongoOperations is the interface that MongoTemplate implements.

Can we connect MongoDB with spring boot?

We need following APIs to work with Spring Boot and MongoDB database. There are two approaches through which we can connect to MongoDB database - MongoRepository and MongoTemplate . We will try to establish what one API offers over another and when should you choose any one of them for your use-case.


2 Answers

1 : Make sure you have spring-data-mongodb

2 : if you are using @CreatedDate or @LastModifiedDate then you don't need any additional configuration.

class ClassName {

    .......

  @CreatedDate
  private DateTime createdDate;

  @LastModifiedDate
  private DateTime @lastModifiedDate;

}

3: if you are using @CreatedBy and @LastModifiedBy then you have to implement AuditorAware<T> SPI interface

class ClassName {

    .......

    @CreatedBy
    private String createdBy;

    @LastModifiedBy
    private String lastModifiedBy;

}

public class AppAuditor implements AuditorAware<String> {

    @Override
    public String getCurrentAuditor() {

        // get your user name here
        return "xxxx";
    }

}

Implementation of AuditorAware based on Spring Security from spring doc

class SpringSecurityAuditorAware implements AuditorAware<User> {

  public User getCurrentAuditor() {

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    if (authentication == null || !authentication.isAuthenticated()) {
      return null;
    }

    return ((MyUserDetails) authentication.getPrincipal()).getUser();
  }
}
like image 74
Chandra Avatar answered Oct 04 '22 07:10

Chandra


Can you check if you have Spring Data MongoDB dependency 1.9.4.RELEASE or above as mongoAuditingHandler requires MappingMongoConverter which is available in version 1.9.4.RELEASE or above as per changelog - spring-data-mongodb-changelog, for example:

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-mongodb</artifactId>
    <version>1.9.4.RELEASE</version>
</dependency>
like image 31
Arpit Aggarwal Avatar answered Oct 04 '22 07:10

Arpit Aggarwal