springboot常见错误,与一些奇怪的问题(仅供参考持续更新中)

以下问题是我在开发中所遇到的一些问题,由于本人能力有限,技术水平一般,以下问题仅供参考

(一)重复接口报错

Error creating bean with name ‘documentationPluginsBootstrapper’ defined in URL [jar:file:/E:/apache-maven-3.6.3/ck/io/springfox/springfox-spring-web/2.6.1/springfox-spring-web-2.6.1.jar!/springfox/documentation/spring/web/plugins/DocumentationPluginsBootstrapper.class]: Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘webMvcRequestHandlerProvider’ defined in URL [jar:file:/E:/apache-maven-3.6.3/ck/io/springfox/springfox-spring-web/2.6.1/springfox-spring-web-2.6.1.jar!/springfox/documentation/spring/web/plugins/WebMvcRequestHandlerProvider.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘requestMappingHandlerMapping’ defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping. Cannot map ‘imgStansController’ method
springboot.imgStans.web.controller.ImgStansController#updateImgStans(ImgStans)

(二)shiro关闭session报错(不支持:subject.getSession (),和roles[]拦截)

org.apache.shiro.subject.support.DisabledSessionException: Session creation has been disabled for the current subject. This exception indicates that there is either a programming error (using a session when it should never be used) or that Shiro’s configuration needs to be adjusted to allow Sessions to be created for the current Subject. See the org.apache.shiro.subject.support.DisabledSessionException JavaDoc for more.

(三)Tomcat的header缓冲区大小不够(TomcatConfig加上protocol.setMaxHttpHeaderSize(8192);)

Invalid character found in method name. HTTP method names must be tokens

(四)连接超时nacos,(上线就行了)

Did not observe any item or terminal signal within 10000ms in ‘map’ (and no fallback has been configured)
at reactor.core.publisher.FluxTimeout T i m e o u t M a i n S u b s c r i b e r . h a n d l e T i m e o u t ( F l u x T i m e o u t . j a v a : 289 )   [ r e a c t o r − c o r e − 3.3.5. R E L E A S E . j a r : 3.3.5. R E L E A S E ] S u p p r e s s e d : r e a c t o r . c o r e . p u b l i s h e r . F l u x O n A s s e m b l y TimeoutMainSubscriber.handleTimeout(FluxTimeout.java:289) ~[reactor-core-3.3.5.RELEASE.jar:3.3.5.RELEASE] Suppressed: reactor.core.publisher.FluxOnAssembly TimeoutMainSubscriber.handleTimeout(FluxTimeout.java:289) [reactorcore3.3.5.RELEASE.jar:3.3.5.RELEASE]Suppressed:reactor.core.publisher.FluxOnAssemblyOnAssemblyException:
Error has been observed at the following site(s):
|_ checkpoint ⇢ Request to GET health [DefaultWebClient]
Stack trace:

(五)mapper层没有@param注解(未找到参数)

Parameter ‘userId’ not found. Available parameters are [arg1, arg0, param1, param2]

(六)升级swager报错加入依赖或不升级

加入依赖

  <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-validation</artifactId>
      <version>2.2.7.RELEASE</version>
      <scope>compile</scope>
      <exclusions>
        <exclusion>
          <artifactId>tomcat-embed-el</artifactId>
          <groupId>org.apache.tomcat.embed</groupId>
        </exclusion>
      </exclusions>

Failed to start bean ‘documentationPluginsBootstrapper’; nested exception is java.lang.NoClassDefFoundError: javax/validation/constraints/NotBlank

(七)关于缺少VCRUNTIME140_1.DLL的解决方案

安装一个:微软常用运行库.exe

(八)springboot无法访问templates下的页面

/**
 * 开启前后端跨域允许
 * 王文斌
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
                .maxAge(3600)
                .allowCredentials(true);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
        registry.addResourceHandler("doc.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("/templates/**").addResourceLocations("classpath:/templates/");
    }


    /**
     * 配置template下的后台html路径
     * @param registry
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addRedirectViewController("/kaptcha","/templates/kaptcha.html");

    }


}

(九)浏览器打开后直接跳转hao123解决方式

hao123篡改了你浏览器的图标:

打开文件所在的位置->找到浏览器_proxy.exe发送到桌面

然后修改图标

(十)字符集错误

Incorrect string value: '\xF0\x9F\xA5\xB4' for column 'nick_name' at row 1

在数据库中将字段字符集改为utf8mb4

(十一)微服务报错跨域(网关解决跨域)

网关加入应许跨域

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.util.pattern.PathPatternParser;

@Configuration
public class CorsConfig {
    @Bean
    public CorsWebFilter corsFilter(){
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsWebFilter(source);
    }

    private CorsConfiguration buildConfig(){
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        //在生产环境上最好指定域名,以免产生跨域安全问题
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("OPTIONS");
        corsConfiguration.addAllowedMethod("POST");
        corsConfiguration.addAllowedMethod("GET");
        return corsConfiguration;
    }
}

子服务去除跨域应许

@Override
public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**")
            .allowedOrigins("*")
            .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
            .maxAge(3600)
            .allowCredentials(true);
}

(十二)微服务报错503

重启网关

(十三)IDEA启动项目报Command line is too long. Shorten command line for XXXApplication or also for

Error running ‘XXXApplication’: Command line is too long. Shorten command line forXXX

项目的文件夹.idea中找到workspace.xml文件在这个标签下

<component name="PropertiesComponent">
    
 </component>

添加

<property name="dynamic.classpath" value="true" />

(十四)slf4j注解log报错

报错原因依赖着 lombok 插件,安装好插件可以解决

(十五) websocket问题

@ServerEndpoint与@Autowired不能一起用

用以下方法

TransUserService transUserService = SpringContextUtil.getBean(TransUserService.class);
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext = null;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if(SpringContextUtil.applicationContext == null){
            SpringContextUtil.applicationContext  = applicationContext;
        }
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static Object getBean(String name){
        return getApplicationContext().getBean(name);
    }

    public static <T> T getBean(Class<T> clazz){
        return getApplicationContext().getBean(clazz);
    }

    public static <T> T getBean(String name,Class<T> clazz){
        return getApplicationContext().getBean(name, clazz);
    }
}

(十六)服务器重启redis连接问题

服务器重启会导致设置的密码失效,重新设置密码,修改代码

(十七)springboot版本过低报错

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'applicationAvailability' defined in class path resource [org/springframework/boot/autoconfigure/availability/ApplicationAvailabilityAutoConfiguration.class]: BeanPostProcessor before instantiation of bean failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceAutoConfiguration': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.boot.context.properties.ConfigurationPropertiesBindException: Error creating bean with name 'spring.datasource.dynamic-com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceProperties': Could not bind properties to 'DynamicDataSourceProperties' : prefix=spring.datasource.dynamic, ignoreInvalidFields=false, ignoreUnknownFields=true; nested exception is java.lang.IllegalStateException: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@e72dba7 has not been refreshed yet

(十八)Springboot整合easyExcel报错

注意:导出会与lombok的@Accessors(chain = true)注解冲突

解决删除@Accessors(chain = true)

(十九)聚合项目下引用所有的包

@SpringBootApplication(scanBasePackages = "com.weerspace")

(二十)java方法强行停止整个服务 System.exit(0);

(二十一)手动导包

mvn install:install-file -Dfile=“引用jar包的路径” -DgroupId=“groupId的内容” -DartifactId=“artifactId的内容” -Dversion=“version的内容” -Dpackaging=jar

mvn install:install-file -Dfile=‘E:\apache-maven-3.6.3\ck\shiku-im-common-1.0.jar’’ -DgroupId=‘‘com.shiku.mongodb’’ -DartifactId=‘‘mongodb-morphia’’ -Dversion=‘‘version1.0’’ -Dpackaging=jar

(二十二)关于nginx反向代理后获取不到客户端的真实ip地址问题

映射改为

location /api {

   proxy_pass http://127.0.0.1:10678/;

   proxy_set_header Host $host;

        proxy_set_header X-Real-IP $remote_addr;

        proxy_set_header REMOTE-HOST $remote_addr;

        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

(二十三)数据库事物问题@Transactional注解

  1. @Transactional只能回滚RuntimeExceptionRuntimeException下面的子类抛出的异常,不能回滚Exception异常。

  2. 如果需要支持回滚Exception异常请用@Transactional(rollbackFor = Exception.class)

    失效场景

    1. 不是用public修饰

    2. try catch捕获了异常

    3. 没有加@Service

    4. 必须加在需要回滚的位置(需要回滚的方法里,或者是在ServiceImpl层写业务)

(二十四)mybatis中的like查询问题

CONCAT('%',#{},'%') 使用CONCAT()函数

%${question}%‘ 可能引起SQL注入

(二十五)项目不需要连接数据库,启动报错

彻底解决Failed to configure a DataSource: ‘url‘ attribute is not specified and no embedded datasource

解决方法如下:

只要在将@SpringBootApplication修改为@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})就可以启动的时候不需要连接数据库。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值