Ошибка в пользовательском интерфейсе репозитория

Я пытаюсь настроить свое первое Java-приложение с использованием Spring Data для MongoDB в многомодульном проекте Maven 3. Вот соответствующие версии:

  • Ява 7
  • монгодб-win32-x86_64-2.2.0
  • Весенние данные 1.1.1.RELEASE
  • Весна 3.2.0.РЕЛИЗ

Я получаю следующую ошибку времени выполнения:

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'actorFacade': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private es.mi.casetools.praetor.persistence.springdata.repositories.ActorRepository es.mi.casetools.praetor.facade.impl.DefaultActorFacade.actorRepository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'actorRepository': FactoryBean threw exception on object creation; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property insert found for type void
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:609)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
    at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:106)
    at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:57)
    at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:100)
    at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:248)
    at org.springframework.test.context.TestContext.loadApplicationContext(TestContext.java:124)
    at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:148)
    ... 30 more

Поискав в google, я нашел людей с такой же проблемой, и, похоже, это связано с пользовательскими репозиториями.

Вот объект, который я хочу сохранить как документ монго.

public class Actor {
    public enum ActorStereotype {
        SYSTEM, 
        PERSON
    }
        private String id;
    private String code; // unique
    private ActorStereotype stereotype;
    private String title; // Short title for the actor
    private String description;
    private String projectId; // project this actor belongs to

        // getters & setters

Стандартный интерфейс репозитория.

public interface ActorRepository extends MongoRepository<Actor, String>, ActorRepositoryCustom {
}

Пользовательский интерфейс (где, я думаю, ошибка живет).

@NoRepositoryBean
public interface ActorRepositoryCustom {
    void updateSingleActor(Actor actor);
    void insertActor(Actor actor);
}

Реализация пользовательского интерфейса.

public class ActorRepositoryCustomImpl implements ActorRepositoryCustom {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void updateSingleActor(Actor actor) {
        if(actor.getId() != null) 
            throw new MissingIdException();

        // TODO change to Spring Converter
        DBObject dbo = (DBObject)mongoTemplate.getConverter().convertToMongoType(actor);

        mongoTemplate.updateFirst(query(where("_id").is(actor.getId())), 
                Update.fromDBObject(dbo, new String[]{}), 
                Actor.class);
    }

    @Override
    public void insertActor(Actor actor) {  
        if(actor.getId() != null) 
            throw new IdProvidedException();

        mongoTemplate.save(actor);
    }

}

И, наконец, контекст приложения.

    <context:annotation-config/>

    <bean id="propertyConfigurer"       class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:properties/test.properties</value>
            </list>
        </property>
    </bean>

    <!-- mongodb configuration -->          
    <mongo:repositories base-package="es.mi.casetools.praetor.persistence.springdata.repositories" 
        mongo-template-ref="mongoTemplate" repository-impl-postfix="Impl">                  
        <repository:exclude-filter type="annotation" expression="org.springframework.data.repository.NoRepositoryBean"/>    
    </mongo:repositories>

    <mongo:mongo id="mongotest" host="${mongo.host}" port="${mongo.port}" write-concern="SAFE">
    </mongo:mongo>

    <mongo:db-factory dbname="${mongo.dbname}" mongo-ref="mongotest"/>

    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
    </bean> 
    <bean id="actorFacade" class="es.mi.casetools.praetor.facade.impl.DefaultActorFacade">
    </bean>

</beans>

У меня также есть небольшой тест Spring, который не загружает вышеуказанный контекст приложения, что приводит к исключению, которое я указал вверху.

Я попытался добавить следующее, но получаю то же исключение.

<bean id="actorRepositoryCustomImpl" class="es.mi.casetools.praetor.persistence.springdata.repositories.ActorRepositoryCustomImpl"></bean>

Кто-нибудь понял, в чем может быть ошибка?


person Taka    schedule 19.12.2012    source источник
comment
Я тоже использую пользовательские репозитории, и у меня не было никаких проблем. Разница в том, что в моей конфигурации spring свойство репозитория-импл-постфикса имеет значение CustomImpl. Попробуйте сделать это!   -  person Miguel Cartagena    schedule 20.12.2012


Ответы (1)


Комментарий Мигеля решил проблему. Я дал неправильное имя классу реализации. Я видел подобные вопросы, поэтому я попытаюсь прояснить решение в надежде, что оно поможет кому-то еще.

У меня есть следующее определение интерфейса

public interface ActorRepository extends MongoRepository<Actor, String>, ActorRepositoryCustom

Определение пользовательского интерфейса выглядит следующим образом:

public interface ActorRepositoryCustom

Итак, моя ошибка заключалась в том, что я назвал реализацию ActorRepositoryCustom с помощью ActorRepositoryCustomImpl, ожидая, что Springdata подберет реализацию, поскольку ее постфикс по умолчанию — Impl. Дело в том, что Springdata по умолчанию ищет ActorRepositoryImpl, даже если вы реализуете ActorRepositoryCustom. Решение использует необязательный атрибут repository-impl-postfix и устанавливает для него значение CustomImpl.

person Taka    schedule 21.12.2012