无法自动装配spring存储库bean

时间:2017-07-18 20:57:57

标签: java database spring javabeans

我继续收到以下错误:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: 
No qualifying bean of type 'StorageItemRepository'

我的beans.xml设置为查找全部 - 位于每个模块资源文件的META-INF / beans.xml中。我的Repository类上有@Repository,我的web.xml肯定配置为查找bean。

值得注意的是 - 这在部署时有效 - 只是不适用于以下单元测试。

我的单元测试:

 /**
 * Test for {@link StorageItemRepository}
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:JDBCConfig.xml"})
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = {"com.app.storage.persistence.repository"})
public class StorageItemRepositoryTest {

/** {@link StorageItemRepository} */
@Autowired
private StorageItemRepository storageItemRepository;

/**
 * Finds all storage items in db.
 */
@Test
public void checkFindAllItems(){

    final StorageItemPersistenceModel storageItemPersistenceModel = new StorageItemPersistenceModel();
    storageItemPersistenceModel.setId(1L);
    storageItemPersistenceModel.setDateStored(new DateTime());
    storageItemPersistenceModel.setName("Name");
    storageItemRepository.save(storageItemPersistenceModel);
}
}

JDBCConfig文件:

<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost:3306/storage_app_schema" />
    <property name="username" value="root" />
    <property name="password" value="dollar123" />
</bean>

<bean id="myEmf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="packagesToScan" value="com.app.storage.persistence.model" />
    <property name="dataSource" ref="dataSource" />
    <property name="jpaVendorAdapter" ref="jpaVendorAdapter"/>
    <property name="persistenceUnitName" value="app_test"/>
    <property name="jpaProperties">
        <props>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.hbm2ddl.auto">update</prop>
        </props>
    </property>
</bean>

<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
    <property name="showSql" value="true"/>
    <property name="generateDdl" value="true"/>
    <property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect"/>
</bean>

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="myEmf"/>
</bean>

</beans>

persistence.xml绝对没问题,并且工作原因不是原因。

1 个答案:

答案 0 :(得分:0)

你是如何进行单元测试的?

由于它在部署时工作,而不是在单元测试中,我倾向于怀疑单元测试执行缺少类路径,例如执行类路径中不存在JDBCConfig.xml