【问题标题】:Consider defining a bean named 'elasticsearchTemplate' in your configuration考虑在配置中定义一个名为“elasticsearchTemplate”的 bean
【发布时间】:2019-10-22 16:22:12
【问题描述】:

我刚刚启动了 springboot 并尝试使用 spring-boot 实现弹性搜索,但是在运行 spring-boot 应用程序时出现这种类型的错误

考虑在您的配置中定义一个名为“elasticsearchTemplate”的 bean。

POM.XML

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-devtools</artifactId>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>4.0.0</version>
        </dependency>
         <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>transport</artifactId>
            <version>5.6.10</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
        
        
    </dependencies>

存储库

@Repository
public interface StudentRepository extends ElasticsearchRepository<Student, Integer>{}

控制器

@RestController
public class Controller {
    
    @Autowired
    StudentRepository studentRepo;
    
    @GetMapping(value="/student/all")
    List<Student> getAllStudent() {
        
        Iterator<Student> studentList = studentRepo.findAll().iterator();
        List<Student> students = new ArrayList<>();
        if(studentList.hasNext()) {
            students.add(studentList.next());
        }
        return students;
    }
    
    @PostMapping(value="/student/add")
    String addStudent(@RequestBody Student student) {
        
        studentRepo.save(student);
        return "Record Added Successfully";
    } 
    
    @DeleteMapping(value="/student/delete/{id}")
    String deleteStudent(@PathVariable int id) {
        
        studentRepo.deleteById(id);
        return "Record Deleted Successfully";
    }
    
    //@GetMapping(value="/student/findById/{id}")
    
}

谁能帮我解决这个错误

考虑在您的配置中定义一个名为“elasticsearchTemplate”的 bean。

【问题讨论】:

    标签: java spring spring-boot elasticsearch elastic-stack


    【解决方案1】:

    您需要在 application.properties 文件中定义一些弹性搜索属性,例如 cluster-nodescluster-names,供 ElasticsearchTemplateElasticsearchRepository 使用以连接到Elasticsearch 引擎。

    你可以参考下面提到的链接:

    https://dzone.com/articles/elasticsearch-with-spring-boot-application

    【讨论】:

      【解决方案2】:

      注意:请参考spring-data-elasticsearch-versionsSpring Data Elasticsearch Changelog(查看所需版本的Elasticsearch version)以检查版本兼容性。

      解决方案(1):


      如果要使用 spring boot 1.x,只需创建一个@Configuration 类并添加一个ElasticsearchOperations Bean。
      请注意,spring boot 1.x 不支持最新版本的 ElasticSearch 5.x 及更高版本。
      cluster.name:请确保您在代码中设置的集群名称为与您在 $ES_HOME/config/elasticsearch.yml 中设置的 cluster.name 相同
      @Configuration
      public class ElasticSearchConfig {
      
          @Bean
          public ElasticsearchOperations elasticsearchTemplate() throws UnknownHostException {
              return new ElasticsearchTemplate(getClient());
          }
      
          @Bean
          public Client getClient() throws UnknownHostException {
              Settings setting = Settings
                  .builder()
                  .put("client.transport.sniff", true)
                  .put("path.home", "/usr/share/elasticsearch") //elasticsearch home path
                  .put("cluster.name", "elasticsearch")
                  .build();
              //please note that client port here is 9300 not 9200! 
              TransportClient client = new PreBuiltTransportClient(setting)
                  .addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9300)); 
              return client;
          }
      }
      
      

      解决方案(2):


      另外,您可以参考这个spring boot issue,它显示了 从 spring boot 2.2.0 开始的 spring 数据中 Elasticsearch 的自动配置。
      因此,使用 spring boot 2.2spring-boot-starter-elasticserach 您无需手动配置 Elasticsearch。

      示例工作项目:
      版本:
      弹簧靴:2.2.0.RELEASE
      弹性搜索:6.6.2

      Pom.xml:

      <?xml version="1.0" encoding="UTF-8"?>
      <project xmlns="http://maven.apache.org/POM/4.0.0"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
          <modelVersion>4.0.0</modelVersion>
      
          <groupId>com.example</groupId>
          <artifactId>spring-boot-elasticsearch</artifactId>
          <version>1.0-SNAPSHOT</version>
      
          <parent>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-starter-parent</artifactId>
              <version>2.2.0.RELEASE</version>
          </parent>
      
          <dependencies>
              <dependency>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
              </dependency>
              <dependency>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-starter-test</artifactId>
                  <scope>test</scope>
              </dependency>
          </dependencies>
      
      </project>
      

      application.properties:

      spring.data.elasticsearch.cluster-name=elasticsearch
      spring.data.elasticsearch.cluster-nodes=localhost:9300
      spring.elasticsearch.jest.uris=http://localhost:9200
      

      主应用程序类:

      import org.springframework.boot.SpringApplication;
      import org.springframework.boot.autoconfigure.SpringBootApplication;
      
      @SpringBootApplication
      public class Application {
          public static void main(String[] args) {
              SpringApplication.run(Application.class, args);
          }
      }
      

      模型类:

      import lombok.*;
      import org.springframework.data.annotation.Id;
      import org.springframework.data.elasticsearch.annotations.Document;
      
      @Document(indexName = "your_index", type = "books")
      public class Book {
          @Id
          private String id;
          private String title;
          private String author;
          private String releaseDate;
          //getter, setter/constructors
      }
      

      存储库类:

      import com.example.model.Book;
      import org.springframework.data.domain.Page;
      import org.springframework.data.domain.Pageable;
      import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
      import org.springframework.stereotype.Repository;
      import java.util.List;
      
      @Repository
      public interface BookRepository extends ElasticsearchRepository<Book, String> {
      
          Page<Book> findByAuthor(String author, Pageable pageable);
          List<Book> findByTitle(String title);
      }
      

      服务类: 一些测试方法:

      import com.example.model.Book;
      import org.springframework.data.domain.Page;
      import org.springframework.data.domain.Pageable;
      import java.util.List;
      
      public interface BookService {
          Book save(Book book);
          void delete(Book book);
          Book findOne(String id);
          Iterable<Book> findAll();
          Page<Book> findByAuthor(String author, Pageable pageable);
          List<Book> findByTitle(String title);
      }
      

      服务实现:

      import com.example.model.Book;
      import com.example.repository.BookRepository;
      import org.springframework.data.domain.Page;
      import org.springframework.data.domain.Pageable;
      import org.springframework.stereotype.Service;
      import java.util.List;
      
      @Service
      public class BookServiceImpl implements BookService {
      
          private BookRepository bookRepository;
      
          public BookServiceImpl(BookRepository bookRepository) {
              this.bookRepository = bookRepository;
          }
      
          @Override
          public Book save(Book book) {
              return bookRepository.save(book);
          }
      
          @Override
          public void delete(Book book) {
              bookRepository.delete(book);
          }
      
          @Override
          public Book findOne(String id) {
              return bookRepository.findById(id).orElse(null);
          }
      
          @Override
          public Iterable<Book> findAll() {
              return bookRepository.findAll();
          }
      
          @Override
          public Page<Book> findByAuthor(String author, Pageable pageable) {
              return bookRepository.findByAuthor(author, pageable);
          }
      
          @Override
          public List<Book> findByTitle(String title) {
              return bookRepository.findByTitle(title);
          }
      }
      
      

      测试类:

      @RunWith(SpringRunner.class)
      @SpringBootTest(classes = Application.class)
      public class BookTest {
      
          @Autowired
          private BookService bookService;
      
          @Autowired
          private ElasticsearchTemplate esTemplate;
      
          @Before
          public void before(){
              esTemplate.deleteIndex(Book.class);
              esTemplate.createIndex(Book.class);
              esTemplate.putMapping(Book.class);
              esTemplate.refresh(Book.class);
          }
      
          @Test
          public void testSave(){
              Book book = new Book("1001", "Elasticsearch", "title", "23-FEB-2017");
              Book testBook = bookService.save(book);
              assertNotNull(testBook.getId());
              assertEquals(testBook.getTitle(), book.getTitle());
              assertEquals(testBook.getAuthor(), book.getAuthor());
              assertEquals(testBook.getReleaseDate(), book.getReleaseDate());
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2017-07-19
        • 2019-03-16
        • 2019-02-26
        • 2020-05-24
        • 2022-01-19
        • 2017-11-14
        • 1970-01-01
        • 2019-01-27
        • 2017-05-01
        相关资源
        最近更新 更多