spring-boot - java.lang.IllegalStateException : Failed to load ApplicationContext , springboot设置

标签 spring-boot elasticsearch redis

错误信息如下

java.lang.IllegalStateException: Failed to load ApplicationContext

at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125) at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108) at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:190) at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:132) at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190) at org.junit.runner.JUnitCore.run(JUnitCore.java:137) at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68) at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47) at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242) at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'wokerLogController': Unsatisfied dependency expressed through field 'client'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'client' defined in class path resource [com/aurora/backend/config/ESConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.elasticsearch.client.Client]: Factory method 'client' threw exception; nested exception is java.lang.IllegalStateException: availableProcessors is already set to [4], rejecting [4] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1378) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:575) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498) at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:846) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:863) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:546) at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775) at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:127) at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99) at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:117) ... 24 more

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'client' defined in class path resource [com/aurora/backend/config/ESConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.elasticsearch.client.Client]: Factory method 'client' threw exception; nested exception is java.lang.IllegalStateException: availableProcessors is already set to [4], rejecting [4] at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:627) at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:456) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1288) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1127) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:538) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498) at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1244) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1164) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593) ... 42 more

Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.elasticsearch.client.Client]: Factory method 'client' threw exception; nested exception is java.lang.IllegalStateException: availableProcessors is already set to [4], rejecting [4] at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:622) ... 55 more Caused by: java.lang.IllegalStateException: availableProcessors is already set to [4], rejecting [4] at io.netty.util.NettyRuntime$AvailableProcessorsHolder.setAvailableProcessors(NettyRuntime.java:51) at io.netty.util.NettyRuntime.setAvailableProcessors(NettyRuntime.java:87) at org.elasticsearch.transport.netty4.Netty4Utils.setAvailableProcessors(Netty4Utils.java:83) at org.elasticsearch.transport.netty4.Netty4Transport.(Netty4Transport.java:112) at org.elasticsearch.transport.Netty4Plugin.lambda$getTransports$0(Netty4Plugin.java:86) at org.elasticsearch.client.transport.TransportClient.buildTemplate(TransportClient.java:189) at org.elasticsearch.client.transport.TransportClient.(TransportClient.java:283) at org.elasticsearch.transport.client.PreBuiltTransportClient.(PreBuiltTransportClient.java:128) at org.elasticsearch.transport.client.PreBuiltTransportClient.(PreBuiltTransportClient.java:114) at org.elasticsearch.transport.client.PreBuiltTransportClient.(PreBuiltTransportClient.java:104) at com.aurora.backend.config.ESConfig.client(ESConfig.java:45) at com.aurora.backend.config.ESConfig$$EnhancerBySpringCGLIB$$d0b29c5a.CGLIB$client$0() at com.aurora.backend.config.ESConfig$$EnhancerBySpringCGLIB$$d0b29c5a$$FastClassBySpringCGLIB$$93c49e6a.invoke() at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244) at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363) at com.aurora.backend.config.ESConfig$$EnhancerBySpringCGLIB$$d0b29c5a.client() at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ... 56 more

一个使用elasticSearch、mysql、redis等的springboot项目。 Google有很多,但他只是一个新的singboot。网上的东西不行。我不知道如何更改它。

application-local.yml

server:
  port: 8000
  servlet:
    context-path: /api/v3
  error:
    whitelabel:
      enabled: false

spring:
  http:
    multipart:

    encoding:
      charset: UTF-8
      force: true
      enabled: true


  datasource:
    url: jdbc:mysql://localhost:3306/aurora?useUnicode=yes&characterEncoding=UTF-8&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
    username: root
    password: 123456789
    driverClassName: com.mysql.jdbc.Driver
  jpa:
    database-platform: org.hibernate.dialect.MySQL57Dialect
    generate-ddl: true
    show-sql: true
  liquibase:
    change-log: classpath:db/db.master.xml
  data:
    elasticsearch:
      cluster-name: elasticsearch
      cluster-nodes: 127.0.0.1:9300
      repositories:
        enabled: true
  redis:
    host: 127.0.0.1
    port: 6379
    password:  
    database: 0
    lettuce:
      pool:
        max-active: 8 
        max-wait: -1 
        max-idle: 8 
        min-idle: 0 
        timeout: 0 
  servlet:
    multipart:
      max-file-size: 200MB # Max file size.
      max-request-size: 215MB # Max Request Size
      enabled: true

logging:
  pattern:
    file: "%d{yy-MM-dd HH:mm:ss.SSS} [%thread] %-5level : %X{user} %logger{36}.%M - %msg%n"
    console: "%d{yy-MM-dd HH:mm:ss.SSS} [%thread] %-5level : %X{user} %logger{36}.%M - %msg%n"
  level:
    org.springframework.web: DEBUG
    guru.springframework.controllers: DEBUG
    org.hibernate: DEBUG

app:
  wechat:
    notification: true
  design:
    root-path: /home/cloudeda/Aurora/UploadData
  jwt:
    base64-secret: NjkwNjU5ZTg0YmYxZmE0ZDJmYmFlNmMwMGNjMjJjZTc4MjFiZjkyNTk3N2IyN2M5OGQyNzg3ZTExN2M1MGYzMzNkNTg2MzMwODgzZTE3YzIwMDdhMTg1Y2M4ZWFmYmFjOGEyYWNiOTU3ZGYzNTY3NDdmMzg3ZWNjNjRmNjdjNzI=
    # Token is valid 24 hours
    token-validity-in-seconds: 86400
    token-validity-in-seconds-for-remember-me: 2592000
  id:
    data-center: 1
    machine: 1


  server:
    broker: tcp://localhost:5555
  flask:
    ibis-parser-url: http://localhost:5050/api/v3/server/parse-ibis-model
    generate-report-url: http://localhost:5050/api/v3/server/report

security:
  user:
    name: aurora
    password: aurora-monitor-password

elasticsearch:
  host: 127.0.0.1
  port: 9300
  cluster:
    name: elasticsearch

应该与ES的配置有关

ESConfig.java

import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.net.InetAddress;
import java.net.UnknownHostException;

@Configuration
public class ESConfig {

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

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

    @Value("${elasticsearch.cluster.name:elasticsearch}")
    private String clusterName;

    public String getHost() {
        return this.host;
    }

    public int getPort() {
        return this.port;
    }

    @Bean
    public Client client() {
        TransportClient client = null;

        Settings settings = Settings.builder()
            .put("cluster.name", clusterName)
            .put("client.transport.ignore_cluster_name", false)
            .build();

        try {
            client = new PreBuiltTransportClient(settings)
                .addTransportAddress(new TransportAddress(InetAddress.getByName(host), port));
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        return client;
    }
}

Controller

import com.aurora.backend.beans.ResultBean;
import com.aurora.backend.beans.WorkerLogBean;
import com.aurora.backend.param.SearchSimulationLogParam;
import com.aurora.backend.security.CurrentUser;
import com.aurora.backend.security.UserPrincipal;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.Client;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping(value = "/es")
@Slf4j
public class WokerLogController {

    @Autowired Client client;

    @PostMapping(value = "/simulation/log")
    public ResultBean getSimulationLog(
        @CurrentUser UserPrincipal user,
        @RequestBody SearchSimulationLogParam param
    ) {

        SearchResponse response = client.prepareSearch("logstash-worker")
            .setTypes("doc")
            .setSearchType(SearchType.QUERY_THEN_FETCH)
            .setQuery(QueryBuilders.matchQuery("logtype", 1))
            .setQuery(QueryBuilders.matchQuery("token", param.getToken()))
            .setPostFilter(
                QueryBuilders.rangeQuery("@timestamp")
                    .from(param.getStartTime()).to(param.getEndTime()))
            .get();

        SearchHit[] hits = response.getHits().getHits();
        List<WorkerLogBean> mapList = new ArrayList<>();
        for (int i = 0; i < hits.length; i++) {
            WorkerLogBean logBean = new WorkerLogBean();
            logBean.setId(hits[i].getId());
            logBean.setLog(hits[i].getSourceAsMap().get("log").toString());
            logBean.setMessage(hits[i].getSourceAsMap().get("message").toString());
            mapList.add(logBean);
        }
        return new ResultBean(mapList);
    }
}

最佳答案

这是您的异常(exception)情况:

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'wokerLogController': Unsatisfied dependency expressed through field 'client'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'client' defined in class path resource

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'client' defined in class path resource [com/aurora/backend/config/ESConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.elasticsearch.client.Client]: Factory method 'client' threw exception; nested exception is java.lang.IllegalStateException: availableProcessors is already set to [4], rejecting [4] at

Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.elasticsearch.client.Client]: Factory method 'client' threw exception; nested exception is java.lang.IllegalStateException: availableProcessors is already set to [4], rejecting [4] at

此问题已在this link中报告。 。 Elasticsearch 没有遇到过这个问题。以下内容可能会解决您的问题,但这可能取决于网络服务器。检查一下。

@Component
public class ElasticSearchConfiguration implements InitializingBean {
    static {
        System.setProperty("es.set.netty.runtime.available.processors", "false");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println(System.getProperty("es.set.netty.runtime.available.processors"));
    }
}

关于spring-boot - java.lang.IllegalStateException : Failed to load ApplicationContext , springboot设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56374784/

相关文章:

spring boot 如何排除依赖依赖中的配置类

java - Spring 中 Autowiring 特定的内部 bean

bash - Elasticsearch bash 脚本不起作用,但如果我复制并粘贴到终端中,它就可以工作

exception - redis.clients.jedis.exceptions.JedisDataException:ERR错误编译脚本(新功能):user_script:1:附近的格式错误的数字

python - 在 redis 中使用管道进行批量处理(python 示例)

java - 上传文件时出现 "Could not delete file C:\Users\..."错误

spring-boot - SpringBoot CascadeType ALL 与 MERGE 和分离实体

elasticsearch - 未知的发现类型[gce]

apache - Elasticsearch 查询上下文与过滤上下文

redis - redis中有get_next之类的东西吗?