2015-04-11 2 views
1

Я создаю простое приложение с Spring, Hibernate и базой данных MySQL. Я провел некоторое исследование, но ответа не было. У меня есть интерфейс репозитория, который является расширением BaseCrudRepository, который расширяет ReadOnlyRepository, который является расширением org.springframework.data.repository.Repository. код, как показано ниже:Не удается autowire Spring Data 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> 

приложение-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> 

Проблема заключается в том, что даже этот простой тест не пройден, потому что хранилище, которое, как предполагается, будет autowired равна нулю:

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. У кого-нибудь есть идея, как здесь можно установить аутсорсинг?

+1

вы никогда не создаете какой-либо контекста Spring в тестовом модуле, и d не проводите тест с помощью тест-драйва Spring. Как весна могла бы автошина bean-компонента внутри вашего теста? Прочтите http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#integration-testing –

+0

Большое спасибо. Я не знаю, чего я ожидал, но я потратил много времени на поиск причины где-то еще ... – mat3e

ответ

2

Это происходит потому, что ваш тестовый класс Spring не знает. Вам нужно:

  1. включает spring-test банки в вашем (тесте) классах через Maven зависимости или других средств
  2. Из теста я могу видеть, что Вы используете TestNG, так что выше баночка сделает для вас доступной в TestNG Spring тест бегун:
  3. аннотировать класс с (предположу, что у вас нет контекста теста, который был бы лучше практикой кстати.):
@ContextConfiguration(locations = { "classpath:app-context.xml" }) 
public class SpringConfigurationTest extends AbstractTestNGSpringContextTests 
{ 
    //... 
} 
+0

Большое спасибо. Я создам контекст для тестов. – mat3e

0

Так что у меня был файл app-context.xml в папке WEB-INF, и я не использовал этот контекст для тестирования. Рабочая версия:

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

    @Autowired 
    private AreaDateRepository adRepo; 

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

} 
Смежные вопросы