spring中@Qualifier注解不生效解决

@Qualifier作用:

通过使用 @Qualifier 注解,我们可以消除需要注入哪个 bean 的问题。用来解决歧义。

在写配置类的时候,自己的@Qualifier注解老是不生效,报Error creating bean with name ‘com.hema.es.es.EsApplicationTests’: Unsatisfied 错误,经过排查终于找到了答案:

配置类:

package com.hema.es.es.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration//将该类声明成一个配置文件
public class ElasticsearchClientConfig {

    @Bean//将此类交给spring进行管理创建
    //在spring配置文件中,id相当于方法名,class相当于返回值
    public RestHighLevelClient getRestHighLevelClient() {
        RestHighLevelClient restHighLevelClient = new RestHighLevelClient(RestClient.builder(new HttpHost(
                "127.0.0.1",9200,"http")));

        return restHighLevelClient;
    }
}

测试:

package com.hema.es.es;

import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.client.RequestOptions;


import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;

@SpringBootTest
class EsApplicationTests {
	@Autowired
	@Qualifier("getRestHighLevelClient")
	RestHighLevelClient client;

	@Test
	public void existsIndex() throws IOException {
		String s = "xiaohua";
		//判断es中的某个索引是否存在
		GetIndexRequest getRequest = new GetIndexRequest(s);

		boolean exists = client.indices().exists(getRequest,RequestOptions.DEFAULT);
		System.out.println(exists);
	}



@Qualifier(“getRestHighLevelClient”)指定的是配置类中的方法名,通过这个的话就可以找到注册到spring容器中的RestHighLevelClient 类

你可能感兴趣的:(问题解决,config)