title: Adding SessionFactory to DAO results in java.lang.IllegalStateException: Failed to load ApplicationContext
body: <p>I'm trying to execute a junit test with Spring autowiring with Hibernate. I believe the issue is due to adding the sessionFactory to the DAO/Repo layer.  When I remove the the sessionFactory and retrieve a non DB value no error messages are thrown. What is really confusing me is that in my junit test case I have a session factory and it can connect to the database. The error I'm having is when I try to couple the DAO/Repo with Autowiring in my junit test case and service layer:</p>
  
  <p>In this scenario both test cases will pass
  <strong>Junit</strong></p>
  
  <pre><code>@RunWith(SpringJUnit4ClassRunner.class)
  @ContextConfiguration(classes= {ProductServiceTestConfig.class})
  public class ProductService_Test {
  
      private static final Logger logger = Logger.getLogger(ShoppingController_Test.class);
  
      @Autowired
      private ProductService productService;
  
  
      @Test
      public void testSC() {
  
          logger.debug("ProductService: Accessing ProductService_Test");
          Product p = productService.getProductDaoMock();
          //System.out.print("!!!!!!!!!!!!!, Mock "+p.getName()+"\n");
          System.out.print("!!!!!!!!!!!!!, DAO "+productService.getProductDaoMock()+"\n");
      }
  
      @Autowired
      SessionFactory sf;
  
  
  
      @Transactional
      public void productList(){
          Session session = sf.getCurrentSession();
          Transaction tx = session.beginTransaction();
          List&lt;Product&gt; products = session.createCriteria(Product.class).list();  
          tx.commit();
          System.out.print("!!!!!!!!"+session.toString());
      }
  </code></pre>
  
  <p><strong>Configuration</strong></p>
  
  <pre><code>@Configuration
  public class ProductServiceTestConfig {
  
  
      @Bean
      public LocalSessionFactoryBean localSessionFactoryBean() {
          Resource config = new ClassPathResource("hibernate.cfg.xml");
          LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
          sessionFactory.setConfigLocation(config);
          //sessionFactory.setPackagesToScan("com.da");
          sessionFactory.setPackagesToScan("com.dao.implementation");
          sessionFactory.setDataSource(dataSource());
          return sessionFactory;
      }
  
  
      @Bean
      public DataSource dataSource() {
          BasicDataSource dataSource = new BasicDataSource();
          dataSource.setDriverClassName("com.mysql.jdbc.Driver");
          dataSource.setUrl("jdbc:mysql://localhost:3306/mydb");
          dataSource.setUsername("root");
          dataSource.setPassword("t3l3com");
  
          return dataSource;
      }
  
  
      @Bean
      @Autowired
      public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
  
         HibernateTransactionManager txManager = new HibernateTransactionManager();
         txManager.setSessionFactory(sessionFactory);
  
         return txManager;
      }
  
      @Bean
      public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
         return new PersistenceExceptionTranslationPostProcessor();
      }
      @Bean
      public ProductDAO ProductDAO() {
          return new ProductDAO();        
      }
  
      @Bean
      public ProductService ProductService(ProductDAO ProductDAO) {
          return new ProductService(ProductDAO);
      }
  
  }
  </code></pre>
  
  <p><strong>Service Layer</strong></p>
  
  <pre><code>import java.io.File;
  import java.nio.file.Path;
  import java.nio.file.Paths;
  import java.util.List;
  
  import org.apache.log4j.Logger;
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.stereotype.Service;
  import org.springframework.web.multipart.MultipartFile;
  import com.dao.implementation.ProductDAO;
  import com.dao.implementation.ProductDAOMock;
  import com.pojo.Product;
  
  @Service
  public class ProductService {
  
      private static final Logger logger = Logger.getLogger(ProductService.class);
  
  
      ProductDAO productDAO;
  
      @Autowired
      public ProductService(ProductDAO productDAO) {
          this.productDAO=productDAO;
      }
  
  
      public Product getProductDaoMock() {
          Product p= productDAO.getProduct();
          return p;
      }
  </code></pre>
  
  <p><strong>REPO</strong></p>
  
  <pre><code>@Repository
  public class ProductDAO implements iProductDAO {
  
  
      private static final Logger logger = Logger.getLogger(ProductDAO.class);
  
  
  
  
      public Product getProduct() {
          Product p = new Product();
          p.setName("Product DAO");
          return p;
      }
  </code></pre>
  
  <p>If I add the following to the <em>Service</em> and Repo layer my test cases will fail.
  <strong>Service</strong></p>
  
  <pre><code>@Service
  public class ProductService {
  
      private static final Logger logger = Logger.getLogger(ProductService.class);
  
  
      ProductDAO productDAO;
  
      @Autowired
      public ProductService(ProductDAO productDAO) {
          this.productDAO=productDAO;
      }
  
  
      public Product getProductDaoMock() {
          Product p= productDAO.getProduct();
          return p;
      }
  
      public void saveProduct(Product product) {
          productDAO.addProduct(product);
  
          MultipartFile productImage = product.getProductImage();
          String rootDirectory = System.getProperty("user.dir");
          Path path = Paths.get(rootDirectory+"\\WEB-INF\\resource\\images\\"+product.getId()+".png");
          logger.debug("Saving to path: "+path);
  
          try {
              logger.info("attempting to save");
              productImage.transferTo(new File(path.toString()));
          } 
          catch (Exception e) {
              e.printStackTrace();
              throw new RuntimeException("Product image saving failed.", e);
          }
  
      }
  
      /*
       * Method that calls the product dao to delete product.
       * 
       */
  
      public void deleteProduct(int id) {
          logger.info("Attempting to delete id"+id);
          productDAO.deleteProduct(id);
      }
  
      /*
       * Method that calls the product dao to edit product.
       * 
       */
  
      public void editProduct(int id) {
          logger.debug("Editing Attempting"+id);
          productDAO.editProduct(id);
      }
  
      /*
       * Method that lists all products.
       * 
       */
  
      public List&lt;Product&gt; listProducts(){
          logger.info("Product Service attempting to get all products");
          List&lt;Product&gt; products = productDAO.getAllProducts();
  
          return products;
  
      }
  
      public Product getProductById(int id) {
          logger.info("ProductService: getProductById"+id);
          ProductDAO pd = new ProductDAO();
          Product product=pd.getProductById(id);
  
          return product;
  
      }
  
  }
  </code></pre>
  
  <p><strong>REPO_Update_fail</strong></p>
  
  <pre><code>@Repository
  public class ProductDAO implements iProductDAO {
  
  
      private static final Logger logger = Logger.getLogger(ProductDAO.class);
  
      @Autowired
      SessionFactory sessionFactory;
  
  
  
  
  
      public Product getProduct() {
          Product p = new Product();
          p.setName("Product DAO");
          return p;
      }
  
  
      public void addProduct(Product product) {
          Session session = sessionFactory.getCurrentSession();
          session.beginTransaction();
          session.saveOrUpdate(product);
          session.getTransaction().commit();
          // Close resources
          sessionFactory.close();
  
      }
  
      public void editProduct(int id) {
          Session session = sessionFactory.getCurrentSession();
          session.beginTransaction();
          Product product = (Product) session.get(Product.class,id);
          session.update(product);
          session.getTransaction().commit();
          //session.close();
          session.flush();
  
  
      }
  
  
      public Product getProductById(int id) {
          Session session = sessionFactory.getCurrentSession();
          Product product = (Product) session.get(Product.class,id);
  
          return product;
      }
  
  
      public List&lt;Product&gt; getAllProducts() {
          Session session = sessionFactory.getCurrentSession();
          List&lt;Product&gt; products = session.createQuery("From Product").list();
          logger.debug("Query List Executed"+session.createQuery("From Product").list());
          session.flush();
  
          return products;
      }
  
  
      public void deleteProduct(int id) {
          Session session = sessionFactory.getCurrentSession();
          session.beginTransaction();
          Product product = (Product) session.get(Product.class,id);
          session.delete(product);
          session.getTransaction().commit();
          //session.close();
          session.flush();
  
      }
  
  }
  </code></pre>
  
  <p><strong>Full Error</strong></p>
  
  <pre><code>49:21,999  WARN GenericApplicationContext:487 - Exception encountered during context initialization - cancelling refresh attempt
  org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ProductService' defined in com.junit.ProductServiceTestConfig: No matching factory method found: factory bean 'productServiceTestConfig'; factory method 'ProductService()'. Check that a method with the specified name exists and that it is non-static.
      at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:549)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1111)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1006)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
      at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
      at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
      at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
      at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
      at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:762)
      at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
      at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
      at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:106)
      at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:57)
      at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:100)
      at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:248)
      at org.springframework.test.context.TestContext.loadApplicationContext(TestContext.java:124)
      at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:148)
      at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:103)
      at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:73)
      at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:313)
      at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211)
      at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:288)
      at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
      at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:284)
      at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
      at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
      at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
      at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
      at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
      at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
      at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
      at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
      at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
      at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
      at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
      at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
      at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
      at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
      at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:542)
      at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:770)
      at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464)
      at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
  01:49:21,999 DEBUG DefaultListableBeanFactory:512 - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@652ce654: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,productServiceTestConfig,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessor,exceptionTranslation,localSessionFactoryBean,transactionManager,ProductService,dataSource,ProductDAO]; root of factory hierarchy
  01:49:21,999 DEBUG DisposableBeanAdapter:245 - Invoking destroy() on bean with name 'localSessionFactoryBean'
  01:49:22,000 DEBUG SessionFactoryImpl:1338 - HHH000031: Closing
  01:49:22,000 DEBUG DisposableBeanAdapter:323 - Invoking destroy method 'close' on bean with name 'dataSource'
  01:49:22,000 ERROR TestContextManager:315 - Caught exception while allowing TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener@26ae880a] to prepare test instance [com.junit.ProductService_Test@348d18a3]
  java.lang.IllegalStateException: Failed to load ApplicationContext
      at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:157)
      at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:103)
      at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:73)
      at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:313)
      at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211)
      at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:288)
      at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
      at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:284)
      at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
      at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
      at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
      at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
      at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
      at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
      at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
      at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
      at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
      at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
      at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
      at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
      at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
      at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
      at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:542)
      at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:770)
      at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464)
      at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
  Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ProductService' defined in com.junit.ProductServiceTestConfig: No matching factory method found: factory bean 'productServiceTestConfig'; factory method 'ProductService()'. Check that a method with the specified name exists and that it is non-static.
      at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:549)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1111)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1006)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
      at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
      at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
      at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
      at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
      at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:762)
      at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
      at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
      at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:106)
      at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:57)
      at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:100)
      at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:248)
      at org.springframework.test.context.TestContext.loadApplicationContext(TestContext.java:124)
      at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:148)
      ... 25 more
  01:49:22,002 DEBUG DirtiesContextTestExecutionListener:112 - After test class: context [[TestContext@60737b23 testClass = ProductService_Test, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration@c038203 testClass = ProductService_Test, locations = '{}', classes = '{class com.junit.ProductServiceTestConfig}', contextInitializerClasses = '[]', activeProfiles = '{}', contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader']]], dirtiesContext [false].
  </code></pre>