Tag Archives: Consider defining a bean of type ‘xxx’ in your configuration. Autowired(required=true)

Consider defining a bean of type ‘xxx’ in your configuration. Autowired(required=true)

 


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

Description:

Field client in com.newpearl.da.service.aggr.dos.saleGoods.OrgAreaSaleGoodsService required a bean of type 'com.newpearl.da.service.es.ElasticsearchRestClient' 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.newpearl.da.service.es.ElasticsearchRestClient' in your configuration.

Strange, the project was originally a good spring boot, but after it was transformed into spring cloud, it reported an error. Bean is not defined

Moreover, the classes are all under the spring boot’s boot class’s subpackage, so there’s no reason why they can’t be scanned

And the startup class also adds a scan package

Startup class.

@SpringBootApplication//spring boot startup class annotation
@EnableScheduling//enable timed tasks
@ComponentScan({"com.newpearl"})///spring scan package path
//@EntityScan("com.newpearl.da.api.model")// package path for jpa entity mapping
@EnableAsync // enable asynchronous methods
@EnableCaching // enable caching
@EnableAspectJAutoProxy//EnableAOP
//@EnableJpaRepositories(basePackages={"com.newpearl.da.biz.dao"})// package path for jpa's Dao layer
@EnableTransactionManagement
@EnableDiscoveryClient// start service discovery
// start Feign client , and specify the class directory of feign, otherwise inject spring to report an error
@EnableFeignClients(basePackages = {"com.newpearl.da.biz.client"})
public class CloudxDAApplication {

    public static void main( String[] args )
    {
        System.out.println( "启动Spring Boot!" );
        SpringApplication.run(CloudxDAApplication.class, args);
    }

Code


@Component
public class ElasticSearchRestClient {

    @Autowired
    private EsConfig esConfig;

    private RestHighLevelClient client;

    public RestHighLevelClient getClient() {
        return this.client;
    }

    public void init() {
        RestClientBuilder builder = RestClient.builder(esConfig.getHost()
                .stream()
                .map(v -> {
                    String[] s = v.split(":");

                    return new HttpHost(s[0], Integer.parseInt(s[1]), esConfig.getScheme());


                }).toArray(HttpHost[]::new))
                .setRequestConfigCallback((config) -> {
                    config.setConnectionRequestTimeout(0)
                            .setSocketTimeout(esConfig.getSocketTimeout())
                            .setConnectTimeout(esConfig.getConnectTimeout());
                    return config;
                });

        if (esConfig.getUsername() != null && !"".equals(esConfig.getUsername())
                && esConfig.getPassword() != null && !"".equals(esConfig.getPassword())) {
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(esConfig.getUsername(), esConfig.getPassword()));

            builder.setHttpClientConfigCallback(httpAsyncClientBuilder ->
                    httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
        }

        client = new RestHighLevelClient(builder);

        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            @Override
            public void run() {
                if (client != null) {
                    try {
                        client.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }));
    }
}

Reference code

@Component
public class OrgAreaSaleGoodsService {

    
    @Autowired
    private ElasticSearchRestClient client;

Solutions

(because it doesn’t look like a problem with the code)

1. In the reference place, change to the constructor injection mode, because the constructor injection priority is higher, explicitly tell the spring container to initialize the bean first

For example

@Component
public class GlobalInitializationTask implements InitializingBean {

    private static final Logger log = LoggerFactory.getLogger(GlobalInitializationTask.class);

    //@Autowired
    private ElasticSearchRestClient client;

    //Changed to constructor injection for more clarity Load order and dependency order    
    @Autowired
    public GlobalInitializationTask(ElasticSearchRestClient client) {

        this.client = client;
    }

The initialization order of Java variables is: static variables or static statement blocks – > Instance variable or initialization statement block – > Construction method – & gt@Autowired

Springboot startup sequence constructor & gt@ Component ( @Autowired > @ PostConstruct )