0

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

package com.customer; 

    import javax.annotation.Resource; 

    import com.customer.repositories.CustomerRepo; 

    @SuppressWarnings("restriction") 
    public class CustomerService { 

     @Resource 
     CustomerRepo custRepo; 

     public void save(Customer cust) { 
      custRepo.save(cust); 
     } 
    } 

=========================================== =======================================

package com.customer; 

    import org.springframework.data.elasticsearch.annotations.Document; 


    @Document(
     indexName = "Customer", type = "cust" 
     ) 
    public class Customer{ 

     private String name; 

     public Customer(String name) { 
      this.name = name; 
     } 

     public String getName() { 
      return this.name; 
     } 
    } 

==== ================================================== ============================

package com.customer.repositories; 

    import com.customer.Customer; 
    import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; 

    public interface CustomerRepo extends ElasticsearchRepository<Customer, String> { 

    } 

=============== ================================================== =================

package com.customer; 

    import org.springframework.context.ApplicationContext; 
    import org.springframework.context.support.ClassPathXmlApplicationContext; 

    public class MainClass { 
     public static void main(String args[]) { 
      ApplicationContext context = 
       new ClassPathXmlApplicationContext(new String[] {"spring-customer.xml"}); 
      CustomerService cust = (CustomerService)context.getBean("customerService"); 
      Customer customer = new Customer("appu"); 
      cust.save(customer); 
     } 

}

Спринг-customer.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:context="http://www.springframework.org/schema/context" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context.xsd"> 

    <context:component-scan base-package="com.customer" /> 

    <import resource="spring-repository.xml"/> 

    <bean id="customerService" class="com.customer.CustomerService" scope="prototype" > 
     <property name="custRepo" ref="custRepo"></property> 
    </bean> 
</beans> 

============================= ================================================== ===

Спринг-repository.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:elasticsearch="http://www.springframework.org/schema/data/elasticsearch" 
    xsi:schemaLocation="http://www.springframework.org/schema/data/elasticsearch http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch-1.0.xsd 
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"> 

    <elasticsearch:transport-client id="client" cluster-nodes="localhost:9300" /> 

    <bean name="elasticsearchTemplate" 
     class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate"> 
     <constructor-arg name="client" ref="client" /> 
    </bean> 

    <elasticsearch:repositories 
     base-package="com.customer.repositories" /> 

The issue is that, I'm getting the following exception: 
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'customerService': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'customerRepo': FactoryBean threw exception on object creation; nested exception is java.lang.NullPointerException 
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:306) 
    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.doGetBean(AbstractBeanFactory.java:313) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193) 
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1105) 
    at com.customer.MainClass.main(MainClass.java:12) 
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'customerRepo': FactoryBean threw exception on object creation; nested exception is java.lang.NullPointerException 
    at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:149) 
    at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.getObjectFromFactoryBean(FactoryBeanRegistrySupport.java:102) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.getObjectForBeanInstance(AbstractBeanFactory.java:1442) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:248) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193) 
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:871) 
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:813) 
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:730) 
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:438) 
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:416) 
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:550) 
    at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:155) 
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:92) 
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:303) 
    ... 7 more 
Caused by: java.lang.NullPointerException 
    at org.springframework.data.elasticsearch.repository.support.MappingElasticsearchEntityInformation.<init>(MappingElasticsearchEntityInformation.java:57) 
    at org.springframework.data.elasticsearch.repository.support.MappingElasticsearchEntityInformation.<init>(MappingElasticsearchEntityInformation.java:49) 
    at org.springframework.data.elasticsearch.repository.support.ElasticsearchEntityInformationCreatorImpl.getEntityInformation(ElasticsearchEntityInformationCreatorImpl.java:46) 
    at org.springframework.data.elasticsearch.repository.support.ElasticsearchRepositoryFactory.getEntityInformation(ElasticsearchRepositoryFactory.java:57) 
    at org.springframework.data.elasticsearch.repository.support.ElasticsearchRepositoryFactory.getTargetRepository(ElasticsearchRepositoryFactory.java:64) 
    at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:147) 
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.getObject(RepositoryFactoryBeanSupport.java:162) 
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.getObject(RepositoryFactoryBeanSupport.java:44) 
    at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:142) 

Похоже, что некоторые вещи не так с моей конфигурацией боба

<bean id="customerService" class="com.customer.CustomerService" scope="prototype" > 
    <property name="custRepo" ref="custRepo"></property> 
</bean> 

CustomerRepository быть интерфейс, как я могу обеспечение соблюдения пружины Автоматического поиска классов реализации.

Примечание: Это нормально работает, когда контейнер выполняет «автопогрузчик». Но при инициализации из bean-файла xml проблема сохраняется.

Может ли кто-нибудь помочь решить эту проблему?

ответ

1

Проблема не в конфигурации боб, но вы должны объявить @Id, как показано ниже в классе Customer

Вы должны иметь Id, чтобы индексировать объект, SD elasticsearch не поддерживает любое юридическое лицо, в индексироваться без идентификатора.

EDIT 1:

==========================

Вам не нужно определить, как обслуживание bean и вручную вводить в него репозиторий. Просто отметьте его @Service и использовать хранилище как @Resource, как указано выше

изменения в файлах

1) CustomerService.java пакет com.customer;

import javax.annotation.Resource; 
import org.springframework.stereotype.Service; 
import com.customer.repositories.CustomerRepo; 

@SuppressWarnings("restriction") 
@Service 
public class CustomerService { 

    @Resource 
    CustomerRepo custRepo; 

    public void save(Customer cust) { 
     custRepo.save(cust); 
    } 
} 

2) spring-customer.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:context="http://www.springframework.org/schema/context" 
     xsi:schemaLocation="http://www.springframework.org/schema/beans 
     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
     http://www.springframework.org/schema/context 
     http://www.springframework.org/schema/context/spring-context.xsd"> 

     <context:component-scan base-package="com.customer" /> 

     <import resource="spring-repository.xml"/> 

</beans> 

Я не тестировал его, но должен работать должным образом.

+0

Thanks Mohsin. Я добавил @Id и во время работы получил следующее исключение – appu

+0

Исключение в потоке «main» org.springframework.beans.factory.BeanCreationException: Ошибка создания bean-компонента с именем «customerService», определенным в ресурсе пути класса [spring-customer.xml] : Не удается разрешить ссылку на bean custRepo при настройке bean-свойства custRepo; вложенное исключение org.springframework.beans.factory.NoSuchBeanDefinitionException: Нет боб под названием «custRepo» не определен \t на org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference (BeanDefinitionValueResolver.java:329) – appu

+0

причиненного: орг. springframework.beans.factory.NoSuchBeanDefinitionException: нет боба под названием «custRepo» не определен \t на org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition (DefaultListableBeanFactory.java:549) – appu

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