Field xxx in xxx required a bean of type xxxthat could not be found

 *************************** APPLICATION FAILED TO START ***************************

 Description:  Field iesService in com.guoke.m.data.manager.ESManager required a bean of type 'com.search.es.api.IESService' that could not be found.  The injection point has the following annotations:  

   - @org.springframework.beans.factory.annotation.Autowired(required=true)   Action:  Consider defining a bean of type 'com.search.es.api.IESService' in your configuration.

***************************应用程序无法启动******************* ********

说明:com.guoke.m.data.manager.ESManager中的iesService字段需要一个类型为com.search.es.api.IESService的bean。注入点具有以下注释:

-@ org.springframework.beans.factory.annotation.Autowired(required = true)操作:考虑在配置中定义类型为“ com.search.es.api.IESService”的bean。

required属性

  • @Autowired(required=true):当使用@Autowired注解的时候,其实默认就是@Autowired(required=true),表示注入的时候,该bean必须存在,否则就会注入失败。
  • @Autowired(required=false):表示忽略当前要注入的bean,如果有直接注入,没有跳过,不会报错。

原因分析及解决

在容器的启动过程中,会初始化很多bean,这也是spring的核心之一(IOC)。但是在注入的过程中,扫描到公共方法中要注入的bean,并未找到,强行注入就会注入失败。我们又不能单独的去除改方法,所以我们采取的思想就是有bean就注入,没有就不注入。解决办法就是@Autowired(required=false)。

但是治标不治本 其实这个方法最主要的原因就是没有实例化我们引用的类  既然没有这个类,导致在使用过程中包空指针,那么,我们就要创建这个类的bean  进行配置bean

例如

package com.deepexi.product.common.config;

import com.search.es.api.ESFactory;
import com.search.es.api.IESService;
import com.search.es.config.SendSearchRequest;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ESConfig {

    @Value("${elasticsearch.host}")
    private String host;

    @Value("${elasticsearch.port}")
    private int port;

    @Bean
    public RestClientBuilder restClientBuilder() {
        HttpHost httpHost = new HttpHost(host, port, "http");
        return RestClient.builder(httpHost);
    }
    @Bean
    public RestHighLevelClient highLevelClient(@Autowired RestClientBuilder restClientBuilder) {
        return new RestHighLevelClient(restClientBuilder);
    }
    @Bean
    public IESService iesService(){
        return ESFactory.createESService();
    }

    @Bean
    public SendSearchRequest sendSearchRequest(){
        return new SendSearchRequest();
    }
}

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值