无法自动装配 Spring 数据存储库

Cannot autowire Spring Data Repository

我正在使用 Spring、Hibernate 和 MySQL 数据库创建一个简单的应用程序。我做了一些研究,但没有一个答案是准确的。我有一个存储库接口,它是 BaseCrudRepository 的扩展,它扩展了 ReadOnlyRepository,它是 org.springframework.data.repository.Repository 的扩展。 代码如下:

package dziecko.repositories;

import dziecko.models.AreaDate;
import dziecko.utils.BaseCrudRepository;

public interface AreaDateRepository extends BaseCrudRepository<AreaDate, Integer> {}

AreaDate 是一个简单的实体:

@Entity
@Table(name = "AREADATES")
public class AreaDate extends AbstractBase implements DtoGenerator<AreaDateDto> {

    private static final long serialVersionUID = -2956040373671316338L;

    @Column(name = "START_TIME")
    private Date startTime;

    @Column(name = "END_TIME")
    private Date endTime;

    @Column(name = "ALARM", nullable = true)
    private Boolean alarm;

    public AreaDate() {    
    }

    public Date getStartTime() {
        return startTime;
    }

    public Date getEndTime() {
        return endTime;
    }

    public Boolean getAlarm() {
        return alarm;
    }

    @Override
    public AreaDateDto createDto() {
        return new AreaDateDto(id, startTime, endTime, alarm);
    }
}

这是我的 web.xml 文件:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/app-context.xml</param-value>
    </context-param>

    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
</web-app>

app-context.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:mvc="http://www.springframework.org/schema/mvc"
    xmlns:beans="http://www.springframework.org/schema/beans" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
    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
    http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

    <!-- Enable @Controller annotation support -->
    <mvc:annotation-driven />

    <jpa:repositories base-package="dziecko.repositories" />

    <context:annotation-config />
    <!-- Scan classpath for annotations (eg: @Service, @Repository etc) -->
    <context:component-scan base-package="dziecko.rests, dziecko.services">
        <context:exclude-filter expression="org.springframework.web.bind.annotation.RestController" type="annotation" />
    </context:component-scan>

    <!-- JDBC Data Source. -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://127.0.0.1:3306/dziecko" />
        <property name="username" value="root" />
        <property name="password" value="" />
        <property name="validationQuery" value="SELECT 1" />
    </bean>

    <!-- Hibernate Session Factory -->
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="jpaVendorAdapter">
         <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
        </property>
        <property name="packagesToScan">
            <array>
                <value>dziecko.models</value>
            </array>
        </property>
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.hbm2ddl.auto">create</prop>
                <prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
                <prop key="hibernate.connection.charSet">UTF-8</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="jadira.usertype.autoRegisterUserTypes">true</prop>
                <prop key="jadira.usertype.databaseZone">jvm</prop>
                <prop key="hibernate.id.new_generator_mappings">true</prop>
            </props>
        </property>
    </bean>

    <!-- Hibernate Transaction Manager -->
    <bean id="transactionManager"
        class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

    <!-- Activates annotation based transaction management -->
    <tx:annotation-driven transaction-manager="transactionManager" />
</beans>

问题是即使这个简单的测试也失败了,因为应该自动装配的存储库是空的:

package dziecko.tests;

import org.springframework.beans.factory.annotation.Autowired;
import org.testng.Assert;
import org.testng.annotations.Test;

import dziecko.repositories.AreaDateRepository;

public class SpringConfigurationTest {

    @Autowired
    private AreaDateRepository adRepo;

    @Test
    public void shouldWireComponents() {
        Assert.assertNotNull(adRepo);
    }
}

java.lang.AssertionError:预期对象不为空

所有实体都在数据库中创建。我只是不知道如何正确配置那些 Spring 存储库。一切似乎都类似于http://docs.spring.io/spring-data/data-commons/docs/1.5.1.RELEASE/reference/html/repositories.html。有人知道如何在这里修复自动装配吗?

所以我在 WEB-INF 文件夹中有 app-context.xml 文件,但我没有附加此上下文进行测试。工作版本:

@ContextConfiguration("/META-INF/app-context.xml")
public class SpringConfigurationTest extends AbstractTestNGSpringContextTests {

    @Autowired
    private AreaDateRepository adRepo;

    @Test
    public void shouldWireComponents() {
        Assert.assertNotNull(adRepo);
    }

}

发生这种情况是因为您的测试 class Spring 不知道。您需要:

  1. 通过 Maven 依赖或其他方式在您的(测试)class路径中包含 spring-test jar
  2. 从你的测试中我可以看到你正在使用 TestNG 所以上面的 jar 将使你可以使用 TestNG Spring 测试运行器:
  3. 注释你的class(假设你没有测试上下文。顺便说一句,这本来是更好的做法):
@ContextConfiguration(locations = { "classpath:app-context.xml" })
public class SpringConfigurationTest extends AbstractTestNGSpringContextTests
{
    //...
}