Spring data mongodb Auditing实现

最近使用mongodb的auditing功能。要在Spring data mongodb 中使@CreatedBy@LastModifiedBy@CreatedBy@LastModifiedBy  这四个注解必须实现AuditorAware接口。

直接上代码:

public class MongodbAuditorAware implements AuditorAware {

    public Optional getCurrentAuditor() {
        HttpSession session = ServletUtils.getSession();
        if(ObjectUtil.isNotNull(session) && ObjectUtil.isNotNull(session.getAttribute(xtzh))){
            return Optional.of((String)session.getAttribute(xtzh));
        }else{
            return Optional.of("system");
        }

    }

}

实体类加上注解:

public class BaseModel implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 主键
     */
    @JSONField(name = "ID")
    @Id
    @Field("_id")
    protected String id;

    /**
     * 创建者
     */
    @CreatedBy
    @JSONField(name = "CJYH")
    @Field("CJYH")
    protected String cjyh;

    /**
     * 创建时间
     */
    @CreatedDate
    @JSONField(name = "CJSJ")
    @Field("CJSJ")
    protected Date cjsj;

    /**
     * 更新者
     */
    @LastModifiedBy
    @JSONField(name = "GXYH")
    @Field("GXYH")
    protected String gxyh;

    /**
     * 更新时间
     */
    @LastModifiedDate
    @JSONField(name = "GXSJ")
    @Field("GXSJ")
    protected Date gxsj;


}

mongodb配置:

@Configuration
@EnableMongoAuditing
public class MongoAuditingConfig {

    @Resource
    ClassScanUtils classScanUtils;
    /**
    * @Description: 
    * @param
    * @return org.springframework.data.domain.AuditorAware
    * @date 2020/5/9 16:55
    */
    @Bean
    public AuditorAware auditorProvider() {
        return new MongodbAuditorAware();
    }

    @Bean
    public MappingMongoConverter mappingMongoConverter(MongoDbFactory factory,
                                                       MongoMappingContext context, BeanFactory beanFactory) throws IOException {
        context.setInitialEntitySet(new HashSet<>(classScanUtils.doScan("com.test.sdf.persistence")));
        context.initialize();
        DbRefResolver dbRefResolver = new DefaultDbRefResolver(factory);
        MappingMongoConverter mappingConverter = new MappingMongoConverter(dbRefResolver, context);

        try {
            mappingConverter.setCustomConversions(beanFactory.getBean(CustomConversions.class));
        } catch (NoSuchBeanDefinitionException ignored) {} // Swallow error

        return mappingConverter;
    }


}
MappingMongoConverter的bean实现要加上,否则会出现“org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.data.mongodb.core.convert.MappingMongoConverter' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}” 错误。
context.setInitialEntitySet()要把mongodb需要auditing的实体类都加上,这里我用了工具类获取所有实体类,代码就不贴了,网上好多。

你可能感兴趣的:(mongodb)