How to access AuditReaderFactory in spring boot application?

…衆ロ難τιáo~ 提交于 2021-02-04 15:41:45

问题


I am using spring boot and spring data jpa. I am also using hibernate envers and I need access to AuditReaderFactory so that I can write Audit Queries.

Since, its a spring boot and spring data jpa, everything is auto configured. So when I do this,

@Autowired
AuditReaderFactory auditReaderFactory;

It doesn't work. I get the following error.

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.hibernate.envers.AuditReaderFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency

How do I get a proper reference to AuditReaderFactory in my repository classes?


回答1:


Following up on above answer, and linked question, I found this to work. (Would be nice if this can be turned into an autowire of the reader directly somehow)

@Autowired
private EntityManagerFactory factory;

public void stuff() {
    AuditReader audit = AuditReaderFactory.get(factory.createEntityManager());
}



回答2:


Create configuration class such as AuditConfiguration.java:

import org.hibernate.envers.AuditReader;
import org.hibernate.envers.AuditReaderFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.persistence.EntityManagerFactory;

@Configuration
public class AuditConfiguration {

    private final EntityManagerFactory entityManagerFactory;

    AuditConfiguration(EntityManagerFactory entityManagerFactory) {
        this.entityManagerFactory = entityManagerFactory;
    }

    @Bean
    AuditReader auditReader() {
        return AuditReaderFactory.get(entityManagerFactory.createEntityManager());
    }
}

After that you can you autowire AuditReader in your component classes.




回答3:


AuditReaderFactory only has two static methods. Can you autowire a SessionFactory object or your EntityMananger? Looks like either would give you what you want, which is access to an AuditReader.

AuditReaderFactory.get(sessionFactory.getCurrentSession())

EDIT this post has some detail or wiring SessionFactory if needed



来源:https://stackoverflow.com/questions/36258677/how-to-access-auditreaderfactory-in-spring-boot-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!