Не удалось загрузить applicationContext: NoSuchBeanDefinitionException при запуске теста JUnit в приложении Spring MVC - PullRequest
0 голосов
/ 26 января 2011

Когда я запускаю:

package se.hsr.web;

import java.util.List;

import junit.framework.Assert;

import se.hsr.web.UserDao;
import se.hsr.web.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration( locations = { "classpath:HSR-servlet.xml" })
public class UserTest {
 private UserDao dao;

 @Autowired
 public void setDao(UserDao dao) {
  this.dao = dao;
 }

 @Test
 public void testCreateData() {
  int expectedResult = 1;
  User user = new User();
  user.setAge(23);
  user.setUserName("Adit");
  user.setRegistered(true);
  dao.saveUser(user);
  Assert.assertEquals(expectedResult, dao.getAllUser(new User()).size());
 }

 @Test
 public void testRetrieveData() {
  List<User> userList = dao.getAllUser(new User());
  Assert.assertEquals(1, userList.size());
  User userExpected = userList.get(0);
  User userResult = dao.selectUserById(userExpected.getUserId());
  Assert.assertEquals(userExpected.getUserId(), userResult.getUserId());
 }

 @Test
 public void testUpdateData() {
  List<User> userList = dao.getAllUser(new User());
  Assert.assertEquals(1, userList.size());
  User userExpected = userList.get(0);
  userExpected.setUserName("Singgih");
  dao.saveUser(userExpected);
  User userResult = dao.selectUserById(userExpected.getUserId());
  Assert.assertEquals(userExpected.getUserName(), userResult
    .getUserName());
 }

 @Test
 public void testDeleteData() {
  List<User> userList = dao.getAllUser(new User());
  Assert.assertEquals(1, userList.size());
  User userExpected = userList.get(0);
  dao.deleteUser(userExpected);
  User userResult = dao.selectUserById(userExpected.getUserId());
  Assert.assertEquals(userResult, null);
 }
}

Вывод консоли:

... 24 more
    Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void se.hsr.web.UserDaoImpl.setSessionFactory(org.hibernate.SessionFactory); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
     at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:589)
     at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84)
     at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:282)
     ... 38 more
    Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
     at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:920)
     at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:789)
     at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:703)
     at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:547)
     ... 40 more

Все мои HSR-servlet.xml, db-config.xml и configuration.properties вПапка src / main / resources.

HSR-servlet.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:component-scan
        base-package="se.hsr.web"/>

    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
    <bean id="propertyConfigurer"
  class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="locations">
   <list>
    <value>/configuration.properties</value>
   </list>
  </property>
 </bean>
</beans>

db-config.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
 xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
 ">
 <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
  destroy-method="close">

  <property name="driverClass">
   <value>${jdbc.driver.className}</value>
  </property>
  <property name="jdbcUrl">
   <value>${jdbc.url}</value>
  </property>
  <property name="user">
   <value>${jdbc.username}</value>
  </property>
  <property name="password">
   <value>${jdbc.password}</value>
  </property>
 </bean>
 <bean id="sessionFactory"
  class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
  <property name="dataSource">
   <ref bean="dataSource" />
  </property>
  <property name="packagesToScan" value="se.hsr.web" />
  <property name="hibernateProperties">
   <props>
    <prop key="hibernate.dialect">${jdbc.hibernate.dialect}</prop>
    <prop key="hibernate.hbm2ddl.auto">create</prop>
    <!-- uncomment this for first time run-->
    <prop key="hibernate.hbm2ddl.auto">create</prop>
    <prop key="hibernate.show_sql">false</prop>
   </props>
  </property>
 </bean>
 <bean id="transactionManager"
  class="org.springframework.orm.hibernate3.HibernateTransactionManager">
  <property name="sessionFactory">
   <ref bean="sessionFactory" />
  </property>
 </bean>
 <tx:annotation-driven />
</beans>

В чем может быть проблема?Благодарю за любую помощь.

ОБНОВЛЕНИЕ:

новое сообщение об ошибке после изменения кода после подсказки от первого комментатора.

Caused by: org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.mchange.v2.c3p0.ComboPooledDataSource] for bean with name 'dataSource' defined in class path resource [db-config.xml]; nested exception is java.lang.ClassNotFoundException: com.mchange.v2.c3p0.ComboPooledDataSource
    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1250)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:433)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:322)
    ... 80 more
Caused by: java.lang.ClassNotFoundException: com.mchange.v2.c3p0.ComboPooledDataSource
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    at org.springframework.util.ClassUtils.forName(ClassUtils.java:257)
    at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:408)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1271)
    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1242)
    ... 86 more

1 Ответ

1 голос
/ 26 января 2011

Попробуйте добавить db-config.xml в ваши конфигурации контекста:

@ContextConfiguration( locations = { "classpath:HSR-servlet.xml", "classpath:db-confix.xml })

Кроме того, я предполагаю, что эта конфигурация работает, когда вы загружаете ее в контейнер сервлета?Это просто модульные тесты, которые не работают?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...