当我尝试使用 Spring Boot 为 SessionFactory 创建 bean 时无法解析的循环引用

Posted

技术标签:

【中文标题】当我尝试使用 Spring Boot 为 SessionFactory 创建 bean 时无法解析的循环引用【英文标题】:Unresolvable circular reference when I try to create the bean for SessionFactory with Spring Boot 【发布时间】:2018-05-08 23:05:26 【问题描述】:

我试图将应用程序与我的数据库连接,但是当我尝试运行它时,我得到了这个错误:

创建名为“barcodeIngDao”的 bean 时出错:通过方法 setSessionFactory' 参数 0 表达的依赖关系不满足;嵌套异常是 org.springframework.beans.factory.UnsatisfiedDependencyException:在 server.Application 中定义名称为 'sessionFactory' 的 bean 创建错误:通过方法 'sessionFactory' 参数 0 表达的不满足依赖关系;嵌套异常是 org.springframework.beans.factory.BeanCurrentlyInCreationException:创建名为“sessionFactory”的 bean 时出错:当前正在创建请求的 bean:是否存在无法解析的循环引用?

barcodeIngDao 只是一个带有 @Repository 的类,它扩展了 GenericDaoHibernate:

package server.util;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

import server.exceptions.InstanceNotFoundException;

public class GenericDaoHibernate<E, PK extends Serializable> implements
GenericDao<E, PK> 

    private SessionFactory sessionFactory;

    private Class<E> entityClass;

    @SuppressWarnings("unchecked")
    public GenericDaoHibernate() 
        this.entityClass = (Class<E>) ((ParameterizedType) getClass()
                .getGenericSuperclass()).getActualTypeArguments()[0];
    

    @Autowired
    public void setSessionFactory(SessionFactory sessionFactory) 
        this.sessionFactory = sessionFactory;
    

    protected Session getSession() 
        return sessionFactory.getCurrentSession();
    

    public void save(E entity) 
        getSession().saveOrUpdate(entity);
    

    public E find(PK id) throws InstanceNotFoundException 
        E entity = (E) getSession().get(entityClass, id);
        if (entity == null) 
            throw new InstanceNotFoundException(id, entityClass.getName());
        
        return entity;
    

    public void remove(PK id) throws InstanceNotFoundException 
        getSession().delete(find(id));
    


这是我的 Application.java:

package server;

import javax.persistence.EntityManagerFactory;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.orm.jpa.vendor.HibernateJpaSessionFactoryBean;

@SpringBootApplication(exclude=HibernateJpaAutoConfiguration.class)
public class Application 

    @Bean
    public HibernateJpaSessionFactoryBean sessionFactory(EntityManagerFactory emf) 
        HibernateJpaSessionFactoryBean fact = new HibernateJpaSessionFactoryBean();
        fact.setEntityManagerFactory(emf);
        return fact;
    

    public static void main(String[] args) 
        SpringApplication.run(Application.class, args);
    

这是我的 application.properties:

spring.datasource.url=jdbc:postgresql://localhost:5432/AppRecipe?useSSL=false
spring.datasource.username=uibRT
spring.datasource.password=uibRT
spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate5.SpringSessionContext

我知道我的 Application.java 与 @SpringBootApplication 中的 @ComponentScan 由于@Repository,它试图为barcodeIngDao 创建bean,barcodeIngDao 扩展了GenericDaoHibernate,因此它尝试在应用程序时为SessionFactory 创建bean .java 它仍处于扫描步骤中,因此尚未为 SessionFactory 创建 bean。

问题是我不知道是否有办法在扫描所有类之前为 SessionFactory 创建 bean,或者我做错了什么,这不是我之前所说的

编辑 如果我尝试这样做:

package server.barcodeing;

import javax.persistence.EntityManagerFactory;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import server.util.GenericDaoHibernate;

@Repository("barcodeIngDao")
public class BarcodeIngDaoHibernate extends
        GenericDaoHibernate<BarcodeIng, Long> implements BarcodeIngDao 

    @Autowired 
    private EntityManagerFactory entityManagerFactory;

    public SessionFactory getSessionFactory()
        return this.entityManagerFactory.unwrap(SessionFactory.class);
    


我得到这个错误:

创建名为“barcodeIngDao”的 bean 时出错:通过方法“setSessionFactory”参数 0 表达的依赖关系不满足;嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException:没有“org.hibernate.SessionFactory”类型的合格 bean 可用:预计至少有 1 个有资格作为自动装配候选者的 bean。

编辑2

如果我删除 Application.java 中的 exclude=HibernateJpaAutoConfiguration.class 我会收到以下错误:

创建名为“org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration”的bean时出错:通过构造函数参数0表示的依赖关系不满足;嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException:没有可用的“javax.sql.DataSource”类型的合格 bean:预计至少有 1 个符合自动装配候选资格的 bean。

编辑3

如果我为此替换 Application.java 中的 SessionFactory 方法:

@Bean
public SessionFactory sessionFactory(@Qualifier("entityManagerFactory") EntityManagerFactory emf) 
     return emf.unwrap(SessionFactory.class);

我收到此错误:

创建名为“barcodeIngDao”的 bean 时出错:通过方法“setSessionFactory”参数 0 表达的依赖关系不满足;嵌套异常是 org.springframework.beans.factory.UnsatisfiedDependencyException:在 server.Application 中定义名称为 'sessionFactory' 的 bean 创建错误:通过方法 'sessionFactory' 参数 0 表达的不满足依赖关系;嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException:没有“javax.persistence.EntityManagerFactory”类型的合格 bean 可用:预计至少有 1 个有资格作为自动装配候选者的 bean。 依赖注解:@org.springframework.beans.factory.annotation.Qualifier (值=entityManagerFactory)

编辑4

将这个依赖项放入pom后,通过edit和edit2,我可以运行服务器:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

现在的问题是当我尝试执行请求时出现此错误:

Servlet.service() 用于路径 [] 上下文中的 servlet [dispatcherServlet] 引发异常 [请求处理失败;嵌套异常是 java.lang.NullPointerException],根本原因 java.lang.NullPointerException 在 server.util.GenericDaoHibernate.getSession(GenericDaoHibernate.java:33)

完全错误:

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause java.lang.NullPointerException
    at server.util.GenericDaoHibernate.getSession(GenericDaoHibernate.java:33)
    at server.util.GenericDaoHibernate.find(GenericDaoHibernate.java:41)
        at server.util.GenericDaoHibernate$$FastClassBySpringCGLIB$$eda6dc96.invoke(<generated>)
        at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
        at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:721)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
        at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:656)
        at server.recipe.RecipeDaoHibernate$$EnhancerBySpringCGLIB$$1857692b.find(<generated>)
        at server.recipeservice.RecipeServiceImpl.findRecipeById(RecipeServiceImpl.java:26)
        at server.recipeservice.RecipeServiceImpl$$FastClassBySpringCGLIB$$1b7b075.invoke(<generated>)
        at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
        at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:721)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
        at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
        at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
        at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:656)
        at server.recipeservice.RecipeServiceImpl$$EnhancerBySpringCGLIB$$14ef69a4.findRecipeById(<generated>)
        at server.controllers.RecipeController.recipeId(RecipeController.java:33)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
        at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
        at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
        at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
        at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
        at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:105)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
        at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)
        at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
        at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459)
        at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.lang.Thread.run(Thread.java:745)

【问题讨论】:

【参考方案1】:

我终于解决了删除GenericDaoHibernate并将barcodeIngDao的扩展更改为CrudRepository:

public interface BarcodeIngRepository extends CrudRepository<BarcodeIng, Long>


【讨论】:

【参考方案2】:

您应该返回一个SessionFactory 实例而不是HibernateJpaSessionFactoryBean。尝试如下替换会话工厂方法。

@Bean
public SessionFactory sessionFactory(@Qualifier("entityManagerFactory") EntityManagerFactory emf) 
     return emf.unwrap(SessionFactory.class);

Here是相关文档。

【讨论】:

它不起作用。我添加了我在编辑中得到的错误3【参考方案3】:

您可以尝试在每个 DAO 类中解开 SessionFactory。

这对我有用..

@Autowired private EntityManagerFactory entityManagerFactory;

public SessionFactory getSessionFactory()
    return this.entityManagerFactory.unwrap(SessionFactory.class);

你试图在 setSessionFactory 方法中创建@autowired 并抛出

通过方法'setSessionFactory'

表达的不满足依赖

删除它并注释 SessionFactory Bean 定义。

我发现你没有使用 Jpa 自动配置

@SpringBootApplication(exclude=HibernateJpaAutoConfiguration.class)

也删除排除参数。

编辑 2: 将此添加到您的 MainClass 中

@PropertySource("classpath:application.properties")

可能它没有读取application.properties 文件。

【讨论】:

这对我不起作用,我添加了我在编辑中遇到的错误 您是否删除了HibernateJpaSessionFactoryBeansetSessionFactory 方法? 我忘了删除 setSessionFactory 方法。现在我收到错误消息,它不存在“javax.persistence.EntityManagerFactory”类型的 bean。我还需要别的吗? @SpringBootApplication(exclude=HibernateJpaAutoConfiguration.class) 这是原因 如果我删除它,它无法识别数据源,我会在 edit2 中显示完整的错误

以上是关于当我尝试使用 Spring Boot 为 SessionFactory 创建 bean 时无法解析的循环引用的主要内容,如果未能解决你的问题,请参考以下文章

当我尝试使用 Hibernate ogm 和 spring boot 时,控制台给出“无法实例化命名策略类”错误

迁移到 Spring Boot 2 并使用 Spring Batch 4

当我进行 Rest api 调用时,使用 Spring Boot 动态创建列/表

清单错误将 spring-boot 启动为 java 应用程序

在java中将对象列表转换为JSON数组 - Spring Boot api测试

Spring boot + Envers ClassNotFoundException