gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 17:25:57 26 4
gpt4 key购买 nike

我正在尝试使用 Spring Autowiring 和 Hibernate 来执行 junit 测试。我认为该问题是由于将 sessionFactory 添加到 DAO/Repo 层造成的。当我删除 sessionFactory 并检索非数据库值时,不会抛出错误消息。真正让我困惑的是,在我的 junit 测试用例中,我有一个 session 工厂,它可以连接到数据库。我遇到的错误是当我尝试在 junit 测试用例和服务层中将 DAO/Repo 与 Autowiring 结合起来时:

在这种情况下,两个测试用例都会通过朱尼特

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

}

服务层

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 协议(protocol)

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

如果我将以下内容添加到服务和存储库层,我的测试用例将失败。服务

@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

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

}

}

完全错误

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

最佳答案

问题出在我的配置文件中:

改变

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

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

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

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

解决了这个问题,看起来是我的 Autowiring 减速问题。

关于java - 将 SessionFactory 添加到 DAO 会导致 java.lang.IllegalStateException : Failed to load ApplicationContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61212229/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com