Bean方法 ‘elasticsearchTemplate’ 在配置中找不到。

huangapple go评论84阅读模式
英文:

Bean method 'elasticsearchTemplate' not able to find in configuration

问题

获取以下错误:


应用启动失败


描述:

com.rahul.es.api.service.QueryDSLService 中的字段模板需要一个类型为 'org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate' 的 bean,但找不到该bean。

注入点具有以下注释:
- @org.springframework.beans.factory.annotation.Autowired(required=true)

找到以下候选项,但无法注入:
- 在 'ElasticsearchDataConfiguration.RestClientConfiguration' 中的 bean 方法 'elasticsearchTemplate' 未加载,因为 @ConditionalOnMissingBean(名称:elasticsearchTemplate 类型:org.springframework.data.elasticsearch.core.ElasticsearchOperations;搜索策略:全部)找到类型为 'org.springframework.data.elasticsearch.core.ElasticsearchOperations' 的 bean elasticsearchTemplate 和找到名为 elasticsearchTemplate 的 bean

操作:

请考虑重新查看上述条目或在配置中定义类型为 'org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate' 的 bean。

EsConfig.java

@Configuration(proxyBeanMethods=false)
@EnableElasticsearchRepositories(basePackages = "com.rahul.es.api.repository")
@ComponentScan(basePackages = { "com.rahul.es.api.service" })
public class EsConfig {

	@Bean
    public RestHighLevelClient client() {
        ClientConfiguration clientConfiguration 
            = ClientConfiguration.builder()
                .connectedTo("localhost:9200")
                .build();
 
        return RestClients.create(clientConfiguration).rest();
    }
 
    @Bean
    public ElasticsearchOperations elasticsearchTemplate() {
        return new ElasticsearchRestTemplate(client());
    }
}

QueryDSLService

@Service
public class QueryDSLService {

	@Autowired
	private ElasticsearchRestTemplate template;

	public List<Customer> searchMultipleField(String firstname, int age) {

		QueryBuilder query = QueryBuilders.boolQuery().must(QueryBuilders.matchQuery("firstname", firstname))
				.must(QueryBuilders.matchQuery("age", age));

		NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder().withQuery(query).build();
		List<Customer> customers = template.queryForList(nativeSearchQuery, Customer.class);
		return customers;
	}

	public List<Customer> getCustomerSearchData(String input) {
		String search = ".*" + input + ".*";
		SearchQuery searchQuery = new NativeSearchQueryBuilder()
				.withFilter(QueryBuilders.regexpQuery("firstname", search)).build();
		List<Customer> customers = template.queryForList(searchQuery, Customer.class);
		return customers;
	}

	public List<Customer> multiMatchQuery(String text) {
		SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(QueryBuilders.multiMatchQuery(text)
				.field("firstname").field("lastname").type(MultiMatchQueryBuilder.Type.BEST_FIELDS)).build();
		List<Customer> customers = template.queryForList(searchQuery, Customer.class);
		return customers;
	}

}

RestController

@SpringBootApplication
@RestController
public class SpringbootElasticsearchQuerydslApplication {
	
	@Autowired
	private QueryDSLService service;

	@GetMapping("/serachMultiField/{firstname}/{age}")
	public List<Customer> serachByMultiField(@PathVariable String firstname, @PathVariable int age) {
		return service.searchMultipleField(firstname, age);
	}

	@GetMapping("/customSearch/{firstName}")
	public List<Customer> getCustomerByField(@PathVariable String firstName) {
		return service.getCustomerSearchData(firstName);
	}

	@GetMapping("/search/{text}")
	public List<Customer> doMultimatchQuery(@PathVariable String text) {
		return service.multiMatchQuery(text);
	}

	public static void main(String[] args) {
		SpringApplication.run(SpringbootElasticsearchQuerydslApplication.class, args);
	}

}
英文:

Getting Below Error:


APPLICATION FAILED TO START


Description:

Field template in com.rahul.es.api.service.QueryDSLService required a bean of type &#39;org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate&#39; that could not be found.

The injection point has the following annotations:
	- @org.springframework.beans.factory.annotation.Autowired(required=true)

The following candidates were found but could not be injected:
	- Bean method &#39;elasticsearchTemplate&#39; in &#39;ElasticsearchDataConfiguration.RestClientConfiguration&#39; not loaded because @ConditionalOnMissingBean (names: elasticsearchTemplate types: org.springframework.data.elasticsearch.core.ElasticsearchOperations; SearchStrategy: all) found beans of type &#39;org.springframework.data.elasticsearch.core.ElasticsearchOperations&#39; elasticsearchTemplate and found beans named elasticsearchTemplate


Action:

Consider revisiting the entries above or defining a bean of type &#39;org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate&#39; in your configuration.

EsConfig.java

@Configuration(proxyBeanMethods=false)
@EnableElasticsearchRepositories(basePackages = &quot;com.rahul.es.api.repository&quot;)
@ComponentScan(basePackages = { &quot;com.rahul.es.api.service&quot; })
public class EsConfig {

	@Bean
    public RestHighLevelClient client() {
        ClientConfiguration clientConfiguration 
            = ClientConfiguration.builder()
                .connectedTo(&quot;localhost:9200&quot;)
                .build();
 
        return RestClients.create(clientConfiguration).rest();
    }
 
    @Bean
    public ElasticsearchOperations elasticsearchTemplate() {
        return new ElasticsearchRestTemplate(client());
    }
}

QueryDSLService

@Service
public class QueryDSLService {

	@Autowired
	private ElasticsearchRestTemplate template;

	public List&lt;Customer&gt; searchMultipleField(String firstname, int age) {

		QueryBuilder query = QueryBuilders.boolQuery().must(QueryBuilders.matchQuery(&quot;firstname&quot;, firstname))
				.must(QueryBuilders.matchQuery(&quot;age&quot;, age));

		NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder().withQuery(query).build();
		List&lt;Customer&gt; customers = template.queryForList(nativeSearchQuery, Customer.class);
		return customers;
	}

	public List&lt;Customer&gt; getCustomerSearchData(String input) {
		String search = &quot;.*&quot; + input + &quot;.*&quot;;
		SearchQuery searchQuery = new NativeSearchQueryBuilder()
				.withFilter(QueryBuilders.regexpQuery(&quot;firstname&quot;, search)).build();
		List&lt;Customer&gt; customers = template.queryForList(searchQuery, Customer.class);
		return customers;
	}

	public List&lt;Customer&gt; multiMatchQuery(String text) {
		SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(QueryBuilders.multiMatchQuery(text)
				.field(&quot;firstname&quot;).field(&quot;lastname&quot;).type(MultiMatchQueryBuilder.Type.BEST_FIELDS)).build();
		List&lt;Customer&gt; customers = template.queryForList(searchQuery, Customer.class);
		return customers;

	}

}

RestController

@SpringBootApplication
@RestController
public class SpringbootElasticsearchQuerydslApplication {
	
	@Autowired
	private QueryDSLService service;

	@GetMapping(&quot;/serachMultiField/{firstname}/{age}&quot;)
	public List&lt;Customer&gt; serachByMultiField(@PathVariable String firstname, @PathVariable int age) {
		return service.searchMultipleField(firstname, age);
	}

	@GetMapping(&quot;/customSearch/{firstName}&quot;)
	public List&lt;Customer&gt; getCustomerByField(@PathVariable String firstName) {
		return service.getCustomerSearchData(firstName);
	}

	
	/**Based on wildcard method */
	@GetMapping(&quot;/search/{text}&quot;)
	public List&lt;Customer&gt; doMultimatchQuery(@PathVariable String text) {
		return service.multiMatchQuery(text);
	}

	public static void main(String[] args) {
		SpringApplication.run(SpringbootElasticsearchQuerydslApplication.class, args);
	}

}

答案1

得分: 1

尝试按照文档所说添加bean名称 https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/#elasticsearch.clients

@Bean(name = { "elasticsearchOperations", "elasticsearchTemplate" })
public ElasticsearchTemplate elasticsearchTemplate() throws UnknownHostException {
    return new ElasticsearchTemplate(elasticsearchClient());
}
英文:

Try to add bean name as the docs says https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/#elasticsearch.clients

@Bean(name = { &quot;elasticsearchOperations&quot;, &quot;elasticsearchTemplate&quot; })
public ElasticsearchTemplate elasticsearchTemplate() throws UnknownHostException {
    return new ElasticsearchTemplate(elasticsearchClient());
}

答案2

得分: 0

不要回答我要翻译的问题。以下是要翻译的内容:

而不是注入 ElasticsearchOperations 的 bean,您需要注入 ElasticsearchRestTemplate,因为错误明确指出,并且还需要将 beanName 从 elasticsearchTemplate 更改为 elasticsearchRestTemplate

@Bean
public ElasticsearchRestTemplate elasticsearchRestTemplate()
{
    return new ElasticsearchRestTemplate(client());
}

注意: 我已在我的一侧进行了测试,因为我刚刚遇到了相同的问题。

英文:

Instead of injecting bean of ElasticsearchOperations, you need to inject ElasticsearchRestTemplate as the error clearly states and change the beanName from elasticsearchTemplate to elasticsearchRestTemplate as well.

    @Bean
    public ElasticsearchRestTemplate elasticsearchRestTemplate()
    {
        return new ElasticsearchRestTemplate(client());
    }

Note: I've tested it on my side as I've just faced same issue.

huangapple
  • 本文由 发表于 2020年10月1日 03:46:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/64144727.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定