java.lang.IllegalStateException:无法加载ApplicationContext,springboot设置

时间:2019-05-30 08:50:09

标签: spring-boot elasticsearch redis

以下是错误消息

  

java.lang.IllegalStateException:无法加载ApplicationContext

     在

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

     

原因:   org.springframework.beans.factory.UnsatisfiedDependencyException:   创建名称为'wokerLogController'的bean时出错:不满意   通过字段“客户”表达的依赖性;嵌套异常为   org.springframework.beans.factory.BeanCreationException:错误   用类路径资源中定义的名称“ client”创建bean   [com / aurora / backend / config / ESConfig.class]:通过Bean实例化   工厂方法失败;嵌套异常为   org.springframework.beans.BeanInstantiationException:失败   实例化[org.elasticsearch.client.Client]:工厂方法“ client”   抛出异常;嵌套的异常是java.lang.IllegalStateException:   availableProcessors已设置为[4],在以下位置拒绝[4]   org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor $ AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596)   在   org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)   在   org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374)   在   org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1378)   在   org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:575)   在   org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498)   在   org.springframework.beans.factory.support.AbstractBeanFactory.lambda $ doGetBean $ 0(AbstractBeanFactory.java:320)   在   org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)   在   org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)   在   org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)   在   org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:846)   在   org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:863)   在   org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:546)   在   org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775)   在   org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)   在   org.springframework.boot.SpringApplication.run(SpringApplication.java:316)   在   org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:127)   在   org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)   在   org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:117)   ...还有24个

     

原因:org.springframework.beans.factory.BeanCreationException:   创建类路径资源中定义的名称为“ client”的bean时出错   [com / aurora / backend / config / ESConfig.class]:通过Bean实例化   工厂方法失败;嵌套异常为   org.springframework.beans.BeanInstantiationException:失败   实例化[org.elasticsearch.client.Client]:工厂方法“ client”   抛出异常;嵌套的异常是java.lang.IllegalStateException:   availableProcessors已设置为[4],在以下位置拒绝[4]   org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:627)   在   org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:456)   在   org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1288)   在   org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1127)   在   org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:538)   在   org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498)   在   org.springframework.beans.factory.support.AbstractBeanFactory.lambda $ doGetBean $ 0(AbstractBeanFactory.java:320)   在   org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)   在   org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)   在   org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)   在   org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277)   在   org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1244)   在   org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1164)   在   org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor $ AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593)   ...还有42

     

原因:org.springframework.beans.BeanInstantiationException:   无法实例化[org.elasticsearch.client.Client]:工厂   方法“客户”抛出异常;嵌套异常为   java.lang.IllegalStateException:availableProcessors已经设置为   [4],在拒绝[4]   org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)   在   org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:622)   ... 55更多原因:java.lang.IllegalStateException:   availableProcessors已设置为[4],在以下位置拒绝[4]   io.netty.util.NettyRuntime $ AvailableProcessorsHolder.setAvailableProcessors(NettyRuntime.java:51)   在   io.netty.util.NettyRuntime.setAvailableProcessors(NettyRuntime.java:87)   在   org.elasticsearch.transport.netty4.Netty4Utils.setAvailableProcessors(Netty4Utils.java:83)   在   org.elasticsearch.transport.netty4.Netty4Transport。(Netty4Transport.java:112)   在   org.elasticsearch.transport.Netty4Plugin.lambda $ getTransports $ 0(Netty4Plugin.java:86)   在   org.elasticsearch.client.transport.TransportClient.buildTemplate(TransportClient.java:189)   在   org.elasticsearch.client.transport.TransportClient。(TransportClient.java:283)   在   org.elasticsearch.transport.client.PreBuiltTransportClient。(PreBuiltTransportClient.java:128)   在   org.elasticsearch.transport.client.PreBuiltTransportClient。(PreBuiltTransportClient.java:114)   在   org.elasticsearch.transport.client.PreBuiltTransportClient。(PreBuiltTransportClient.java:104)   在com.aurora.backend.config.ESConfig.client(ESConfig.java:45)处   com.aurora.backend.config.ESConfig $$ EnhancerBySpringCGLIB $$ d0b29c5a.CGLIB $ client $ 0()   在   com.aurora.backend.config.ESConfig $$ EnhancerBySpringCGLIB $$ d0b29c5a $$ FastClassBySpringCGLIB $ 93c49e6a.invoke()   在   org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244)   在   org.springframework.context.annotation.ConfigurationClassEnhancer $ BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363)   在   com.aurora.backend.config.ESConfig $$ EnhancerBySpringCGLIB $$ d0b29c5a.client()   在sun.reflect.NativeMethodAccessorImpl.invoke0(本机方法)处   sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)   在   sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)   在java.lang.reflect.Method.invoke(Method.java:498)在   org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)   ...还有56个

一个使用弹性搜索,mysql,redis等的springboot项目。 Google有很多,但他只是一个新的spingboot。在线的东西不起作用。我不知道如何更改。

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;
    }
}

控制器

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

2 个答案:

答案 0 :(得分:0)

这是您的例外情况:

  

原因:   org.springframework.beans.factory.UnsatisfiedDependencyException:   创建名称为'wokerLogController'的bean时出错:不满意   通过字段“客户”表达的依赖性;嵌套异常为   org.springframework.beans.factory.BeanCreationException:错误   创建在类路径资源中定义的名称为“ client”的bean

  

原因:org.springframework.beans.factory.BeanCreationException:   创建类路径资源中定义的名称为“ client”的bean时出错   [com / aurora / backend / config / ESConfig.class]:通过Bean实例化   工厂方法失败;嵌套异常为   org.springframework.beans.BeanInstantiationException:失败   实例化[org.elasticsearch.client.Client]:工厂方法“ client”   抛出异常;嵌套的异常是java.lang.IllegalStateException:   availableProcessors已设置为[4],拒绝位于[p]的[4]

  

原因:org.springframework.beans.BeanInstantiationException:   无法实例化[org.elasticsearch.client.Client]:工厂   方法“客户”抛出异常;嵌套异常为   java.lang.IllegalStateException:availableProcessors已经设置为   [4],拒绝[4],

已在this link中报告了此问题。弹性搜索还没有遇到这个问题。以下内容可能会解决您的问题,但这可能取决于Web服务器。检查一下。

@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"));
    }
}

答案 1 :(得分:0)

这可能是一个依赖性问题。无论如何,如果您使用的是Spring Boot2。,请使用rest客户端而不是已弃用的transport客户端。

使用以下代码: build.gradle:

| Name | Count | Time | Language | Diag | 
------------------------------------------------------------- 
| query | 10 | 2015-12-09T17:12:09Z | en-US | 2 | 
| test1 | 16 | 2015-12-09T17:12:09Z | en-US | 2 | .....

版本:应该兼容

compile "com.fasterxml.jackson.datatype:jackson-datatype-hppc"
    compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310"
    compile "com.fasterxml.jackson.datatype:jackson-datatype-hibernate5"
    compile "com.fasterxml.jackson.core:jackson-annotations"
    compile "com.fasterxml.jackson.core:jackson-databind"
    compile "com.fasterxml.jackson.module:jackson-module-afterburner"
    runtime group: 'com.fasterxml.jackson.module', name: 'jackson-modules-java8', version: '2.9.8', ext: 'pom'
    // https://mvnrepository.com/artifact/com.fasterxml.jackson.module/jackson-module-parameter-names
compile group: 'com.fasterxml.jackson.module', name: 'jackson-module-parameter-names', version: '2.9.8'

compile 'org.elasticsearch:elasticsearch'
    compile 'org.elasticsearch.client:transport'
    compile 'org.elasticsearch.client:elasticsearch-rest-client'
    compile 'org.elasticsearch.client:elasticsearch-rest-high-level-client'

    compile 'org.springframework.data:spring-data-elasticsearch'

ElasticSearchConfiguration:

org.elasticsearch.client:elasticsearch-rest-client -> 6.4.3 (*)
org.elasticsearch.client:elasticsearch-rest-high-level-client -> 6.4.3
org.elasticsearch:elasticsearch -> 6.4.3
org.springframework.data:spring-data-elasticsearch -> 3.1.4.RELEASE
com.fasterxml.jackson.datatype:jackson-datatype-hppc -> 2.9.8
com.fasterxml.jackson.core:jackson-core:2.9.8
com.fasterxml.jackson.core:jackson-databind:2.9.8 (*)
com.fasterxml.jackson.datatype:jackson-datatype-jsr310 -> 2.9.8 (*)
com.fasterxml.jackson.datatype:jackson-datatype-hibernate5 -> 2.9.8
com.fasterxml.jackson.core:jackson-annotations -> 2.9.0
com.fasterxml.jackson.module:jackson-module-afterburner -> 2.9.8
com.fasterxml.jackson.module:jackson-module-parameter-names:2.9.8 (*)
com.fasterxml.jackson.module:jackson-modules-java8:2.9.8