SpringCloud常见异常及解决方案

1.Failed to configure a DataSource

***************************
APPLICATION FAILED TO START
***************************
 
Description:
 
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
 
Reason: Failed to determine a suitable driver class
 
 
Action:
 
Consider the following:
    If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
    If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).

在准备配置数据库(数据库框架、JDBC、数据源、sql驱动等)之前不要引入相关依赖即可。如模块本身不需要数据库而有如上报错,需要检查是否存在对数据库相关依赖的间接依赖或误导入。

2.An attempt was made to call a method that does not exist

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

Description:

An attempt was made to call a method that does not exist. The attempt was made from the following location:

    org.apache.catalina.authenticator.AuthenticatorBase.startInternal(AuthenticatorBase.java:1319)

The following method did not exist:

    'java.lang.String javax.servlet.ServletContext.getVirtualServerName()'

The calling method's class, org.apache.catalina.authenticator.AuthenticatorBase, was loaded from the following location:

    jar:file:/D:/Java/apache-maven-3.8.6/repository/org/apache/tomcat/embed/tomcat-embed-core/9.0.65/tomcat-embed-core-9.0.65.jar!/org/apache/catalina/authenticator/AuthenticatorBase.class

The called method's class, javax.servlet.ServletContext, is available from the following locations:

    jar:file:/D:/Java/apache-maven-3.8.6/repository/javax/servlet/servlet-api/2.5/servlet-api-2.5.jar!/javax/servlet/ServletContext.class
    jar:file:/D:/Java/apache-maven-3.8.6/repository/org/apache/tomcat/embed/tomcat-embed-core/9.0.65/tomcat-embed-core-9.0.65.jar!/javax/servlet/ServletContext.class

The called method's class hierarchy was loaded from the following locations:

    javax.servlet.ServletContext: file:/D:/Java/apache-maven-3.8.6/repository/javax/servlet/servlet-api/2.5/servlet-api-2.5.jar


Action:

Correct the classpath of your application so that it contains compatible versions of the classes org.apache.catalina.authenticator.AuthenticatorBase and javax.servlet.ServletContext


解决过程:

1.注意到报错有

The called method's class, javax.servlet.ServletContext, is available from the following locations:
    jar:file:/D:/Java/apache-maven-3.8.6/repository/javax/servlet/servlet-api/2.5/servlet-api-2.5.jar!/javax/servlet/ServletContext.class
    jar:file:/D:/Java/apache-maven-3.8.6/repository/org/apache/tomcat/embed/tomcat-embed-core/9.0.65/tomcat-embed-core-9.0.65.jar!/javax/servlet/ServletContext.class

有多个包的类重名,由于我们做微服务同时需要Eureka和Tomcat,不能直接删除。所以首先尝试排除javax中的冲突类:

     <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>2.3</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <filters>
                                <filter>
                                    <artifact>javax.servlet</artifact>
                                    <excludes>
                                        <exclude>/javax/ServletContext.class</exclude>
                                    </excludes>
                                </filter>
                            </filters>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

之后运行,提示

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'configDataContextRefresher' defined in class path resource [org/springframework/cloud/autoconfigure/RefreshAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.cloud.context.refresh.ConfigDataContextRefresher]: Factory method 'configDataContextRefresher' threw exception; nested exception is java.lang.NoClassDefFoundError: org/springframework/boot/logging/DeferredLogFactory
	at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:657) ~[spring-beans-5.2.12.RELEASE.jar:5.2.12.RELEASE]
	at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:637) ~[spring-beans-5.2.12.RELEASE.jar:5.2.12.RELEASE]
	(省略栈追踪...)
	... 28 common frames omitted

导致Bean注入失败,显然行不通。

检查依赖,发现在内置tomcat的springcloud之外还多了spring-boot-starter-tomcat,去掉之后,问题解决。

3.Error creating bean with name xxx…

类似于

org.springframework.beans.factory.BeanCreationException: Error creating bean with name'configurationPropertiesBeans' defined in class path resource 

这样的异常提示,加上大量的栈追踪。

原因同上,更新版本相对应的SpringBoot和SpringCloud(见官方文档Spring Cloud)。解决版本适配后运行,提示

  • ***************************
    APPLICATION FAILED TO START
    *********************	******
    
    Description:
    
    An attempt was made to call a method that does not exist. The attempt was made from the following location:
    
        org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration$StandardGsonBuilderCustomizer.customize(GsonAutoConfiguration.java:90)
    
    The following method did not exist:
    
        'com.google.gson.GsonBuilder com.google.gson.GsonBuilder.setLenient()'
    
    The calling method's class, org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration$StandardGsonBuilderCustomizer, was loaded from the following location:
    
        jar:file:/C:/Users/xxx/.m2/repository/org/springframework/boot/spring-boot-autoconfigure/2.7.3/spring-boot-autoconfigure-2.7.3.jar!/org/springframework/boot/autoconfigure/gson/GsonAutoConfiguration$StandardGsonBuilderCustomizer.class
    
    The called method's class, com.google.gson.GsonBuilder, is available from the following locations:
    
        jar:file:/C:/Users/xxx/.m2/repository/com/google/code/gson/gson/2.1/gson-2.1.jar!/com/google/gson/GsonBuilder.class
        
    The called method's class hierarchy was loaded from the following locations:
    
        com.google.gson.GsonBuilder: file:/C:/Users/xxx/.m2/repository/com/google/code/gson/gson/2.1/gson-2.1.jar
    
    
    Action:
    
    Correct the classpath of your application so that it contains compatible versions of the classes org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration$StandardGsonBuilderCustomizer and com.google.gson.GsonBuilder
    
    
    进程已结束,退出代码1
    
    

笔者这里并没有引用GsonBuilder相关包,于是追踪到GsonBuilder所在类,在启动类注解@SpringBootApplication作如下改动:

@SpringBootApplication(exclude = {GsonAutoConfiguration.class})

问题解决。

4.Failed to start bean ‘documentationPluginsBootstrapper’

org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException: Cannot invoke "org.springframework.web.servlet.mvc.condition.PatternsRequestCondition.getPatterns()" because "this.condition" is null
	at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:181) ~[spring-context-5.3.22.jar:5.3.22]

swagger和springboot版本冲突。建议提高swagger版本

5.Unresolved plugin: 'org.apache.maven.plugins

Unresolved plugin: 'org.apache.maven.plugins:maven-jar-plugin:2.4'

Unresolved plugin: 'org.apache.maven.plugins:maven-compiler-plugin:3.1'

Unresolved plugin: 'org.apache.maven.plugins:maven-surefire-plugin:2.12.4'

Unresolved plugin: 'org.apache.maven.plugins:maven-install-plugin:2.4'

Unresolved plugin: 'org.apache.maven.plugins:maven-site-plugin:3.3'

解决方案:加入下述依赖:

  <dependency>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-install-plugin</artifactId>
            <version>2.4</version>
            <type>maven-plugin</type>
        </dependency>

        <dependency>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-deploy-plugin</artifactId>
            <version>2.7</version>
            <type>maven-plugin</type>
        </dependency>

        <dependency>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.12.4</version>
            <type>maven-plugin</type>
        </dependency>

        <dependency>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-site-plugin</artifactId>
            <version>3.3</version>
            <type>maven-plugin</type>
        </dependency>

6.springdoc进入swagger后台提示:springdoc Failed to load remote configuration.

来自GitHub**bnasslahsen**的回答:

For serving external Urls, from the same swagger-ui, you need to have CORS enabled, on your applications.

@Bean
    public WebMvcConfigurer corsConfigurer()
    {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedOrigins("*");
            }
        };
    }

加入上述bean后,问题解决。之后想复现这个问题,删掉bean仍未触发,原因存疑。

7.三层架构下的500错误

首先需要检查的当然是是否存在环境配置问题。如果环境配置正常,Controller和Service向下传参正常,但返回的对象是空值,那么:

  1. 你大概没有开启mybatis下划线命名转驼峰。

  2. 实体类变量名数据库变量名拼写不一致。

  3. 实体类缺少空参构造器。

  4. controller路径重复而传参不同(通常见于RESTful风格下)导致的调用问题,这种情况下可以发现service没有被调用,而上述情况三层架构都是正常调用而返回空对象。

(很弱智的一个问题,但是之前卡过我一晚上)

8.整合Sentinel后启动:The Bean Validation API is on the classpath but no implementation could be found

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

Description:

The Bean Validation API is on the classpath but no implementation could be found

Action:

Add an implementation, such as Hibernate Validator, to the classpath

另外一个堪称人类迷惑的提示。在某微服务项目引入sentinel时出现,该项目跟Validation API不说是联系密切,也可以说是毫不相关了。推测是sentinel内部引用了Hibernate的Validator,由于版本问题未能做到很好的兼容。

8.1首先尝试的是按照建议加入 Hibernate Validator依赖

<dependency>
    <groupId>org.hibernate.validator</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>8.0.0.Final</version>
</dependency>

报错依旧,所以应该与之无关。(有网友称该问题引入依赖后可以解决,此处存疑)

8.2尝试排除Validation API

@SpringBootApplication(exclude = javax.validation.Validation.class)

加入上述exclude,显然也不能达成效果(因为会导致其他错误:The following classes could not be excluded because they are not auto-configuration classes)

8.3最终解决

引入SpringCloud自带的validation

	<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-validation</artifactId>
    </dependency>

项目运行,启动正常。

9.sentinel-dashboard.jar启动:java.lang.IllegalStateException: Cannot load configuration class:com.alibaba.csp.sentinel.dashboard.DashboardApplication

启动换用下述命令:

java -Dserver.port=8080 -Dcsp.sentinel.dashboard.server=localhost:8080 -Dproject.name=sentinel-dashboard --add-opens java.base/java.lang=ALL-UNNAMED --add-opens java.base/sun.net.util=ALL-UNNAMED -jar sentinel-dashboard-1.8.3.jar

10.sentinel整合nacos启动,提示DataSource flow build error

[Sentinel Starter] DataSource flow build error: Error creating bean with name 'flow-sentinel-nacos-datasource': Lookup method resolution failed; nested exception is java.lang.IllegalStateException: Failed to introspect Class [com.alibaba.cloud.sentinel.datasource.factorybean.NacosDataSourceFactoryBean] from ClassLoader 

解决:引入依赖

<dependency>
    <groupId>com.alibaba.csp</groupId>
    <artifactId>sentinel-datasource-nacos</artifactId>
</dependency>

11.Error creating bean with name ‘redisConnectionFactory‘ defined in class path resource

引入redis做缓存时报出的依赖。解决方案:引入下方依赖

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
</dependency>

12.不算异常的问题:springboot整合Druid后后者监控中心404

解决:加入下述配置类

package com.zjy.dataprovider8000.config;


import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

//这样的方式不需要在启动类头上添加注解:@ServletComponentScan
@Configuration
public class DruidConfig {

    /**
     * 注册一个StatViewServlet
     * @return
     */
    @Bean
    public ServletRegistrationBean DruidStatViewServle(){

        //org.springframework.boot.context.embedded.ServletRegistrationBean提供类的进行注册.
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");

        //添加初始化参数:initParams

        //白名单:
        servletRegistrationBean.addInitParameter("allow","127.0.0.1");

        //IP黑名单 (存在共同时,deny优先于allow) : 如果满足deny的话提示:Sorry, you are not permitted to view this page.
        servletRegistrationBean.addInitParameter("deny","192.168.0.114");

        //登录查看信息的账号密码.
        servletRegistrationBean.addInitParameter("loginUsername","admin");
        servletRegistrationBean.addInitParameter("loginPassword","123456");

        //是否能够重置数据.
        servletRegistrationBean.addInitParameter("resetEnable","false");
        return servletRegistrationBean;
    }

    /**
     * 注册一个:filterRegistrationBean
     * @return
     */
    @Bean
    public FilterRegistrationBean druidStatFilter(){
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());

        //添加过滤规则.
        filterRegistrationBean.addUrlPatterns("/*");

        //添加不需要忽略的格式信息.
        filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");

        return filterRegistrationBean;
    }
}
Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐