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 のすべてのインターフェースを実装してラップする独自のプロキシを注入する必要がありますが、具象クラスのインスタンスではありません。インターフェイスを使用することの全体的なポイントは、オブジェクトの具象型を使用するのではなく、オブジェクトを参照するときにそれらを使用することであるため、それは問題ではListありません ( type ではなく List を参照するために type を使用するのと同じようにArrayList)。

于 2014-01-26T10:01:12.080 に答える