*************************** 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();
}
}