Spring / maven多模块项目:NoUniqueBeanDefinitionException

时间:2015-05-21 00:37:40

标签: java spring maven spring-mvc

我有一个带有Spring的maven多模块项目。我有一个 核心项目 ,它包含所有数据访问bean以及entityManagerFactoryBean。

现在我有另一个maven模块项目,它从 Core项目的 上下文xml文件中导入上下文xml。我试图通过在 API项目 中指定它来覆盖entityManagerFactory bean:

 <beans:bean parent="entityManagerFactory">
    <beans:property name="packagesToScan">
        <beans:array>
            <beans:value>com.blah.data.domains</beans:value>
            <beans:value>com.blah.api.domains</beans:value>
        </beans:array>
    </beans:property>
</beans:bean>

此bean配置位于 核心项目 中:

  <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="persistenceUnitName" value="entityManager"/>
    <property name="packagesToScan" value="com.blah.data.domains" />
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
            <property name="showSql" value="true" />
            <property name="generateDdl" value="true" />
            <property name="databasePlatform" value="org.hibernate.dialect.PostgreSQLDialect" />
        </bean>
    </property>
    <!-- put any ORM specific stuff here -->
    <property name="jpaProperties">
        <props>
            <prop key="hibernate.hbm2ddl.auto">none</prop>
        </props>
    </property>
</bean>

正如您在API项目中看到的那样,我正在向com.blah.api.domains属性添加packagesToScan。问题是我遇到了这个问题:

 Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined: expected single matching bean but found 2: entityManagerFactory,entityManagerFactory$child#0

1 个答案:

答案 0 :(得分:3)

不要试图覆盖API模块中的entityManagerFactory,只需在核心模块中放置通配符即可扫描包。

 <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="persistenceUnitName" value="entityManager"/>
    <property name="packagesToScan" value="com.blah.*.domains" />
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
            <property name="showSql" value="true" />
            <property name="generateDdl" value="true" />
            <property name="databasePlatform" value="org.hibernate.dialect.PostgreSQLDialect" />
        </bean>
    </property>
    <!-- put any ORM specific stuff here -->
    <property name="jpaProperties">
        <props>
            <prop key="hibernate.hbm2ddl.auto">none</prop>
        </props>
    </property>
</bean>

使用com.blah.*.domains将扫描并加载所有域名。