简体   繁体   English

Spring boot mongodb审计报错

[英]Spring boot mongodb auditing error

I'm trying to configure mongodb auditing in my spring boot app, and I having this error when trying to persist my domain class:我正在尝试在我的 Spring Boot 应用程序中配置 mongodb 审计,并且在尝试保留域类时出现此错误:

java.lang.IllegalArgumentException: Couldn't find PersistentEntity for type class com.example.hateoasapi.domain.Post!

Docs from here https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#auditing says that all this configs enough, but I don't know why it doesn't work in my project.来自这里的文档https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#auditing说所有这些配置都足够了,但我不知道为什么它在我的项目。 Could someone help me?有人可以帮助我吗?

My mongodb config class:我的 mongodb 配置类:

    package com.example.hateoasapi.config;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.config.EnableMongoAuditing;
import org.springframework.data.mongodb.core.MongoTemplate;

import com.mongodb.MongoClient;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

import java.util.Collection;
import java.util.Collections;


@Configuration
@EnableMongoAuditing
@EnableMongoRepositories(value = "com.example.hateoasapi.repository")
public class MongoConfig extends AbstractMongoConfiguration {

    @Value("${spring.data.mongodb.database}")
    private String databaseName;

    @Value("${spring.data.mongodb.host}")
    private String databaseHost;

    @Value("${spring.data.mongodb.port}")
    private Integer databasePort;

    @Override
    protected String getDatabaseName() {
        return this.databaseName;
    }

    @Bean
    @Override
    public MongoClient mongoClient() {
        return new MongoClient(databaseHost, databasePort);
    }

    @Bean
    public MongoTemplate mongoTemplate() {
        return new MongoTemplate(mongoClient(), databaseName);
    }

    @Override
    protected Collection<String> getMappingBasePackages() {
        return Collections.singleton("com.example.hateoasapi.domain");
    }
}

AuditorAware implementation: AuditorAware 实现:

package com.example.hateoasapi.config;


import com.example.hateoasapi.domain.User;
import org.springframework.data.domain.AuditorAware;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.Optional;

@Component
public class SecurityAuditor implements AuditorAware<User> {

    @Override
    public Optional<User> getCurrentAuditor() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

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

        return Optional.of((User) authentication.getPrincipal());
    }
}

And my domain class:我的域类:

package com.example.hateoasapi.domain;

import javax.persistence.Id;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;

import org.joda.time.DateTime;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
import org.springframework.hateoas.ResourceSupport;
import com.fasterxml.jackson.annotation.JsonCreator;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import static org.springframework.hateoas.mvc.ControllerLinkBuilder.*;

import java.io.Serializable;
import java.util.List;

import com.example.hateoasapi.controller.*;

@Getter
@Setter
@ToString
@Document
public class Post extends ResourceSupport implements Serializable {

    @Id
    @Field(value = "_id")
    private String objectId;

    @DBRef
    private List<Comment> comments;

    @DBRef
    private User author;

    @NotBlank
    private String body;

    @NotBlank
    private String title;

    private String categoryId;

    @NotEmpty(message = "Tags cannot be empty")
    private List<PostTag> tags;

    @CreatedDate
    private DateTime createdDate;

    @LastModifiedDate
    private DateTime lastModifiedDate;

    @CreatedBy
    private User createdBy;

    private Long views;    
    private List<PostRating> likes;
    private List<PostRating> dislikes;


    @JsonCreator
    public Post() {}

    public Post(String title, String body) {
        this.body = body;
        this.title = title;
    }

    public Post(User author, String body, String title, String categoryId, List<PostTag> tags) {
        this.author = author;
        this.body = body;
        this.title = title;
        this.categoryId = categoryId;
        this.tags = tags;
    }

    public void addLinks() {
        this.add(linkTo(methodOn(PostController.class).getAllPosts(null)).withSelfRel());
    }
}

I solved this issue with the next configuration:我用下一个配置解决了这个问题:

@Configuration
@EnableMongoRepositories(basePackages = "YOUR.PACKAGE")
@EnableMongoAuditing
public class MongoConfig extends AbstractMongoConfiguration {

    @Value("${spring.data.mongodb.host}")
    private String host;

    @Value("${spring.data.mongodb.port}")
    private Integer port;

    @Value("${spring.data.mongodb.database}")
    private String database;

    @Override
    public MongoClient mongoClient() {
        return new MongoClient(host, port);
    }

    @Override
    protected String getDatabaseName() {
        return database;
    }

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

    @Bean
    public MongoDbFactory mongoDbFactory() {
        return new SimpleMongoDbFactory(mongoClient(), database);
    }
}

just add the bean for MongoTemplate with the constructor of MongoTemplate(MongoDbFactory mongoDbFactory, @Nullable MongoConverter mongoConverter)只需添加豆类的MongoTemplate与构造MongoTemplate(MongoDbFactory mongoDbFactory, @Nullable MongoConverter mongoConverter)

Quoting from JIRA ticket引用JIRA 票证

You need to pipe the MappingMongoConverter that's available in the environment into MongoTemplate as well, ie use new MongoTemplate(dbFactory, converter).您还需要通过管道将环境中可用的 MappingMongoConverter 导入 MongoTemplate,即使用 new MongoTemplate(dbFactory, converter)。 The constructor you use is for convenience, one-off usages.您使用的构造函数是为了方便,一次性使用。 We usually recommend to use AbstractMongoConfiguration in case you'd like to customize anything MongoDB specific as this makes sure the components are wired together correctly.我们通常建议使用 AbstractMongoConfiguration 以防您想自定义任何特定于 MongoDB 的内容,因为这可以确保组件正确连接在一起。

More specifically, you need to inject pre-configured MappingMongoConverter or if you need to use your own converter, at least use pre-configured MongoMappingContext.更具体地说,您需要注入预配置的 MappingMongoConverter,或者如果您需要使用自己的转换器,至少使用预配置的 MongoMappingContext。

I had this problem also with spring boot 2.2 I had both @EnableMongoRepositories and @EnableMongoAuditing as configuration and i got the error Couldn't find PersistentEntity for type class我在 spring boot 2.2 中也遇到了这个问题,我有@EnableMongoRepositories@EnableMongoAuditing作为配置,但出现错误无法找到类型类的 PersistentEntity

the problem in my case was the structure of the packages: Application class was a level lower than part of my model that used auditing.就我而言,问题是包的结构:应用程序类的级别低于我使用审计的模型的一部分。

I found on many forum posts that the 2 annotations are not compatible together in spring 2.2, but after restructuring the packages I was able to use both with success in spring boot 2.2我在许多论坛帖子中发现这两个注释在 spring 2.2 中不兼容,但是在重组包之后,我能够在 spring boot 2.2 中成功使用这两个注释

If you use the last version of Spring boot (2.0) and Spring Data, @EnableMongoAuditing @EnableMongoRepositories are not compatible.如果您使用最新版本的 Spring Boot (2.0) 和 Spring Data,@EnableMongoAuditing @EnableMongoRepositories 不兼容。 It's the same with EnableReactiveMongoRepositories annotation.与 EnableReactiveMongoRepositories 注释相同。

If you want to enable mongo auditing, you need to remove your MongoConfig class, use config file to define your mongodb connection and everything will work.如果你想启用 mongo 审计,你需要删除你的 MongoConfig 类,使用配置文件来定义你的 mongodb 连接,一切都会工作。

If you use the last version of Spring boot (2.0) and Spring Data, @EnableMongoAuditing and @EnableMongoRepositories, try remove @EnableMongoRepositories.如果您使用最新版本的 Spring Boot (2.0) 和 Spring Data、@EnableMongoAuditing 和 @EnableMongoRepositories,请尝试删除 @EnableMongoRepositories。 It should be working just this sample project - https://github.com/hantsy/spring-reactive-sample/tree/master/boot-data-mongo它应该只工作这个示例项目 - https://github.com/hantsy/spring-reactive-sample/tree/master/boot-data-mongo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM