SpringBoot项目中遇到的问题

693 阅读2分钟

@MapperScan 引起的问题

如果mapperscan扫描的包路径和@ComponentScan或者@SpringBootApplication(scanBasePackages = {"com.aop.test"})路径有重复,会导致包下面的service类的接口类也会被注入,所以mappscan的包路径单纯只扫描mapper目录下的即可(mapper不要加@Mapper注解)

也可能会引起一下问题:

www.twblogs.net/a/5d29a41cb…

执行sql报错 nested exception is java.sql.SQLException: Connection has already been closed

原因:www.modb.pro/db/171346

解决办法:把druid的removeAbandoned属性设置为false,这个属性是移除超过removeAbandonedTimeout(单位秒)的数据库链接,防止因为数据库链接在规定时间没有关闭导致数据库链接池爆满。

如果执行一个很长的时间的业务,如初始化业务,就会导致数据库链接被关闭,因此建议生成环境关闭这个属性。

springboot java应用程序 设置代理

在编辑启动参数时 选择vm选项 ,添加下面参数

-DsocksProxyHost=192.168.1.185 -DsocksProxyPort=7890

spring cors 跨域配置问题

java.lang.IllegalArgumentException: When allowCredentials is true, allowedOrigins cannot contain the special value "*"since that cannot be set on the "Access-Control-Allow-Origin" response header. To allow credentials to a set of origins, list them explicitly or consider using "allowedOriginPatterns" instead

配置跨域springboot web 跨域,启动的时候出现这个错误

我的配置如下:

在Controller类上添加注解

@CrossOrigin(origins = "*", allowCredentials = "true")

重写WebMvcConfigurer

@Override
public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**") //匹配所有url 相当于全局配置
            .allowedOrigins("*")  //允许所有来源
            .allowCredentials(true)
            .allowedMethods("*")  //允许所有方法
            .allowedHeaders("*")  //允许所有请求头
            .maxAge(1800L);  //有效期2小时
}

Cors Filter

 @Bean
    public FilterRegistrationBean<CorsFilter> corsFilter(){
        //创建 UrlBasedCorsConfigurationSource 配置源,类似 CorsRegistry 注册表
        UrlBasedCorsConfigurationSource configurationSource = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowedOrigins(Collections.singletonList("*"));
        corsConfiguration.setAllowCredentials(true);
        //允许所有请求Method
        corsConfiguration.addAllowedMethod("*");
        //允许所有请求header
        corsConfiguration.setAllowedHeaders(Collections.singletonList("*"));
        //有效期1800秒
        corsConfiguration.setMaxAge(1800L);
        //匹配所有的url
        configurationSource.registerCorsConfiguration("/**", corsConfiguration);
        //创建过滤器
        FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(configurationSource));
        //设置order顺序 保证对跨域请求首先进行拦截
        bean.setOrder(0);
        return bean;
    }

问题在于设置了allowCredentials(允许转递cookie)为true,不能使用allowedOrigins = "*"这个参数,要替换为allowedOriginPatterns="*"

参考:stackoverflow.com/questions/6…

Springboot web 整合Swagger2 问题

Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
  • springboot 版本:2.7.9
  • swagger 版本: 2.9.2

解决方法如下:

@Configuration
//标记项目启用Swagger API接口文档
@EnableSwagger2
//加上这个注解就可以了
@EnableWebMvc
public class SwaggerConfiguration {
......
}

参考: stackoverflow.com/questions/7…