spring中@Qualifier注解不生效解决

本文介绍了如何使用@Qualifier注解在Spring中精确注入所需Bean,解决了配置类中创建Bean后,在测试类中通过@Autowired和@Qualifier注解报错的问题。示例展示了在配置类中定义RestHighLevelClient Bean,并在测试类中正确注入的方法。
摘要由CSDN通过智能技术生成

@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 类

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值