0

我对 Spring 的依赖 jnjection 有一个大问题。我创建了一个ObjectJPA实现我的 DAO 接口的类。现在我想在 JUnit 测试用例中测试它。但我得到一个NoSuchBeanDefinitionException.

这是测试的开始:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:Spring-Common.xml" })
public class Test {

  @Autowired
  ObjectJPA jpa;

}

这就是豆子

package model.dao.jpa;

@Repository
public class ObjectJPA implements ObjectDAO { … }

Spring-Common.xml 的内容

<bean class="….ObjectJPA" />

接口声明

package model.dao;

public interface ObjectDAO {

Spring-Common.xml 的内容

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:p="http://www.springframework.org/schema/p"
       xmlns:tx="http://www.springframework.org/schema/tx"
   xmlns:context="http://www.springframework.org/schema/context"
   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.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

   <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

   <context:component-scan base-package="model.dao.jpa" />

   <bean class="model.dao.jpa.ObjectJPA" />
   <bean id="entityManagerFactory"  class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
     <property name="persistenceUnitName" value="model" />
     <property name="persistenceXmlLocation" value="classpath*:META-INF/persistence.xml" />
     <property name="jpaVendorAdapter">
       <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
     </property>
   </bean>

   <context:annotation-config />
   <tx:annotation-driven />

 </beans>

你有什么想法?您需要哪些信息才能获得更好的影响?

4

1 回答 1

1

对于 Spring,bean 的实际类型是它的接口类型,而不是它的具体类型。所以你应该有

@Autowired
private ObjectDAO jpa;

并不是

@Autowired
private ObjectJPA jpa;

事实上,Spring 默认使用 Java 接口代理来实现 AOP。因此它需要注入自己的代理,该代理实现你的 bean 的所有接口并包装它,但不是它的具体类的实例。这不是问题,因为使用接口的全部意义在于在引用对象时使用它们,而不是使用对象的具体类型(就像您使用 typeList来引用 List 而不是 type一样ArrayList)。

于 2014-01-26T10:01:12.080 回答