当前位置: 首页 > 知识库问答 >
问题:

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

沈旻
2023-03-14

我试图将应用程序与我的数据库连接起来,但当我试图运行它时,我遇到了以下错误:

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);
    }
}

下面是我的应用程序.属性:

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
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);
    }

}

如果删除application.java中的exclude=HibernateJpaAutoConfiguration.class,则会出现以下错误:

创建名为“org.springframework.boot.autocigure.orm.jpa.hibernatejpaAutoConfiguration”的bean时出错:通过构造函数参数0表示的依赖项不满足;嵌套异常为org.springframework.beans.factory.noSuchBeanDefinitionException:没有“javax.sql.datasource”类型的合格bean可用:至少需要一个合格的自动候选bean。

编辑3

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

创建名为“barcode ingdao”的bean时出错:通过方法“set sessionfactory”参数0表示的依赖项不满足;嵌套异常为org.springframework.beans.factory.unsatisfieddependencyexception:创建服务器中定义的名称为“session factory”的bean时出错。application:通过方法“session factory”参数0表示的未满足的依赖关系;嵌套异常为org.springframework.beans.factory.noSuchBeanDefinitionException:没有“javax.persistence.EntityManagerFactory”类型的合格bean可用:应至少有一个合格的自动候选bean。依赖项注释:{@org.SpringFramework.Beans.Factory.Annotation.Qualifier(Value=EntityManagerFactory)}

编辑4

使用edit和edit2after将此依赖项放入pom中,我可以运行服务器

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
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个答案

卢光誉
2023-03-14

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

对我来说是工作..

@Autowired private EntityManagerFactory entityManagerFactory;

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

您正尝试在setSessionFactory方法中创建@Autowired并抛出

@SpringBootApplication(exclude=HibernateJpaAutoConfiguration.class)

@PropertySource({“classpath:application.properties”})

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

 类似资料:
  • 一切都开始了,因为Spring Cloud AWS没有正确配置SimpleStorage原型解决方案。此类负责在使用ResourceLoader时处理s3://协议。有关更多详细信息,请参阅问题:无法在Spring AWS示例上强制转换为org.springframework.core.io.WritableResource。 所以,我不得不手动创建它。但我也在使用LocalStack解决方案(h

  • 我有一个批处理配置。我看到批处理过程默认使用。相反,我需要使用MySQL按批处理发送所有执行细节。但是当我使用以下代码时,我收到以下错误, 创建名称为“batchDataSource”的 Bean 时出错:请求的 Bean 当前正在创建中:是否存在无法解析的循环引用? 在我正在使用属性文件中, 我错过了什么?我正在使用JPA。甚至为什么它不使用可用的JPA数据源?如何在MemoryMap中强制Sp

  • 我正在从事SpringBoot与Spring集成项目。升级应用程序时,我遇到以下错误(仅在pivotal cloud上,而不是本地)- 上下文初始化期间遇到异常-取消刷新尝试:org。springframework。豆。工厂未满足的依赖项异常:创建名为“cloudDataBaseConfiguration”的bean时出错:通过字段“cloud”表示未满足的依赖项:创建名为“cloudMultiH

  • 我已经在我的Spring Boot应用程序中实现了一个调度程序例程,使用Quartz Scheduler遵循本教程(sping-boo-quitz-demo),并为我的目的做了一些修改。 例如,我的作业服务必须能够列出数据库中的所有对象及其子对象,设置新值并最终更新。所有这些都必须是事务性的。 出于某种原因,MyWork类不允许在其中声明事务性方法,所以我通过注入一个带有事务性方法的新服务类来解决

  • 所以我正在构建一个程序,从用户输入中获取int。我有一个非常简单的try/catch块,如果用户没有输入int,应该重复这个块,直到他们输入int为止。以下是代码的相关部分: 如果我为第二个整数输入一个0,那么try/catch完全按照它应该做的做,并让我再次输入它。但是,如果我有一个InputMismatchException,比如为其中一个数字输入5.5,它只是在一个无限循环中显示我的错误消息

  • 当我启动Weblogic时(使用jar:hibernate-core-4.3.6.final.jar和hibernate-jpa-2.1-api-1.0.0.final.jar),遇到以下错误信息: 无法自动连接字段:private org.hibernate.sessionFactory com.nscorp.lars.shopleveling.core.dao.impl.Dataloaddao