title: Unresolvable circular reference when I try to create the bean for SessionFactory with Spring Boot
body: <p>I was trying to connect the application with my database but when I try to run it I get this error: </p>
  
  <blockquote>
    <p>Error creating bean with name 'barcodeIngDao': Unsatisfied dependency expressed through method setSessionFactory' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sessionFactory' defined in server.Application: Unsatisfied dependency expressed through method 'sessionFactory' parameter 0; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'sessionFactory': Requested bean is currently in creation: Is there an unresolvable circular reference?</p>
  </blockquote>
  
  <p>The barcodeIngDao is just a class with @Repository that extends the GenericDaoHibernate:</p>
  
  <pre><code>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&lt;E, PK extends Serializable&gt; implements
  GenericDao&lt;E, PK&gt; {
  
      private SessionFactory sessionFactory;
  
      private Class&lt;E&gt; entityClass;
  
      @SuppressWarnings("unchecked")
      public GenericDaoHibernate() {
          this.entityClass = (Class&lt;E&gt;) ((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));
      }
  
  }
  </code></pre>
  
  <p>This is my Application.java:</p>
  
  <pre><code>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);
      }
  }
  </code></pre>
  
  <p>And here is my application.properties:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>I understand that my Application.java with the @ComponentScan in the @SpringBootApplication it's trying to create the bean for barcodeIngDao because of the @Repository, and the barcodeIngDao extends the GenericDaoHibernate so it tries to create the bean for SessionFactory when the Application.java it's still in the scan step so it hasn't create the bean for SessionFactory yet. </p>
  
  <p>The problem it's that I don't know if there is a way to create the bean for the SessionFactory before scan all the classes, or if I'm doing something wrong and it isn't what I said before</p>
  
  <p><strong>Edit</strong>
  If I try to this:</p>
  
  <pre><code>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&lt;BarcodeIng, Long&gt; implements BarcodeIngDao {
  
      @Autowired 
      private EntityManagerFactory entityManagerFactory;
  
      public SessionFactory getSessionFactory(){
          return this.entityManagerFactory.unwrap(SessionFactory.class);
      }
  
  }
  </code></pre>
  
  <p>I get this error: </p>
  
  <blockquote>
    <p>Error creating bean with name 'barcodeIngDao': Unsatisfied dependency expressed through method 'setSessionFactory' parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.hibernate.SessionFactory' available: expected at least 1 bean which qualifies as autowire candidate.</p>
  </blockquote>
  
  <p><strong>Edit2</strong></p>
  
  <p>If I delete the exclude=HibernateJpaAutoConfiguration.class in the Application.java I get this error:</p>
  
  <blockquote>
    <p>Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javax.sql.DataSource' available: expected at least 1 bean which qualifies as autowire candidate.</p>
  </blockquote>
  
  <p><strong>Edit3</strong></p>
  
  <p>If I replace the SessionFactory method in Application.java for this:</p>
  
  <pre><code>@Bean
  public SessionFactory sessionFactory(@Qualifier("entityManagerFactory") EntityManagerFactory emf) {
       return emf.unwrap(SessionFactory.class);
  }
  </code></pre>
  
  <p>I get this error:</p>
  
  <blockquote>
    <p>Error creating bean with name 'barcodeIngDao': Unsatisfied dependency expressed through method 'setSessionFactory' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sessionFactory' defined in server.Application: Unsatisfied dependency expressed through method 'sessionFactory' parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javax.persistence.EntityManagerFactory' available: expected at least 1 bean which qualifies as autowire candidate.
    Dependency annotations: {@org.springframework.beans.factory.annotation.Qualifier
    (value=entityManagerFactory)}</p>
  </blockquote>
  
  <p><strong>Edit4</strong></p>
  
  <p>With the edit and the edit2 after put this dependency in the pom, I can run the server: </p>
  
  <pre><code>&lt;dependency&gt;
      &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
      &lt;artifactId&gt;spring-boot-starter-jdbc&lt;/artifactId&gt;
  &lt;/dependency&gt;
  </code></pre>
  
  <p>The problem now it's when I try to do a request I get this error:</p>
  
  <blockquote>
    <p>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)</p>
  </blockquote>
  
  <p>Full error:</p>
  
  <pre><code>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(&lt;generated&gt;)
          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(&lt;generated&gt;)
          at server.recipeservice.RecipeServiceImpl.findRecipeById(RecipeServiceImpl.java:26)
          at server.recipeservice.RecipeServiceImpl$$FastClassBySpringCGLIB$$1b7b075.invoke(&lt;generated&gt;)
          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(&lt;generated&gt;)
          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)
  </code></pre>