简体   繁体   English

将 SessionFactory 添加到 DAO 导致 java.lang.IllegalStateException: Failed to load ApplicationContext

[英]Adding SessionFactory to DAO results in java.lang.IllegalStateException: Failed to load ApplicationContext

I'm trying to execute a junit test with Spring autowiring with Hibernate.我正在尝试使用 Spring 自动装配 Hibernate 执行 junit 测试。 I believe the issue is due to adding the sessionFactory to the DAO/Repo layer.我相信问题是由于将 sessionFactory 添加到 DAO/Repo 层。 When I remove the the sessionFactory and retrieve a non DB value no error messages are thrown.当我删除 sessionFactory 并检索非 DB 值时,不会引发错误消息。 What is really confusing me is that in my junit test case I have a session factory and it can connect to the database.真正让我困惑的是,在我的 junit 测试用例中,我有一个 session 工厂,它可以连接到数据库。 The error I'm having is when I try to couple the DAO/Repo with Autowiring in my junit test case and service layer:我遇到的错误是当我尝试在我的 junit 测试用例和服务层中将 DAO/Repo 与自动装配耦合时:

In this scenario both test cases will pass Junit在这种情况下,两个测试用例都将通过Junit

@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<Product> products = session.createCriteria(Product.class).list();  
        tx.commit();
        System.out.print("!!!!!!!!"+session.toString());
    }

Configuration配置

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

}

Service Layer服务层

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

REPO回购协议

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

If I add the following to the Service and Repo layer my test cases will fail.如果我将以下内容添加到Service和 Repo 层,我的测试用例将失败。 Service服务

@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<Product> listProducts(){
        logger.info("Product Service attempting to get all products");
        List<Product> 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;

    }

}

REPO_Update_fail REPO_Update_fail

@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<Product> getAllProducts() {
        Session session = sessionFactory.getCurrentSession();
        List<Product> 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();

    }

}

Full Error完全错误

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].

The issue was in my Configuration file:问题出在我的配置文件中:

Changing改变

   @Bean
    public ProductDAO ProductDAO() {
        return new ProductDAO();        
    }

    @Bean
    public ProductService ProductService(ProductDAO ProductDAO) {
        return new ProductService(ProductDAO);
    }

TO

   @Bean
    public ProductDAO ProductDAO() {
        return new ProductDAO();        
    }

    @Bean
    public ProductService ProductService() {
        return new ProductService();
    }

Solved the issue looks like it was problem in my autowiring deceleration.解决了这个问题,看起来像是我的自动装配减速问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 java.lang.IllegalStateException:无法加载ApplicationContext - java.lang.IllegalStateException: Failed to load ApplicationContext SpringBoot + Mybatis + MySQL,java.lang.IllegalStateException:无法加载ApplicationContext - SpringBoot + Mybatis + MySQL, java.lang.IllegalStateException: Failed to load ApplicationContext 测试 java.lang.IllegalStateException: 加载 ApplicationContext 失败 - Test java.lang.IllegalStateException: Failed to load ApplicationContext @WebMvcTest 失败,出现 java.lang.IllegalStateException:无法加载 ApplicationContext - @WebMvcTest fails with java.lang.IllegalStateException: Failed to load ApplicationContext Junit错误:java.lang.IllegalStateException:无法加载ApplicationContext - Junit error :java.lang.IllegalStateException: Failed to load ApplicationContext Spring JUnit-java.lang.IllegalStateException:无法加载ApplicationContext - Spring JUnit - java.lang.IllegalStateException: Failed to load ApplicationContext 测试失败:java.lang.IllegalStateException:加载ApplicationContext失败 - Test Failure : java.lang.IllegalStateException: Failed to load ApplicationContext java.lang.IllegalStateException: Failed to load ApplicationContext: snakeyaml 依赖问题 - java.lang.IllegalStateException: Failed to load ApplicationContext: snakeyaml dependency issue java.lang.IllegalStateException:添加 JpaSpecificationExecutor 后无法加载 ApplicationContext<Customer> - java.lang.IllegalStateException: Failed to load ApplicationContext after adding JpaSpecificationExecutor<Customer> java.lang.IllegalStateException:无法加载 ApplicationContext 错误 java spring-boot - java.lang.IllegalStateException: Failed to load ApplicationContext error java spring-boot
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM