项目中遇到的错误

项目中遇到的错误

swagger2 和 swagger3

swagger2swagger3 需要导入的依赖

        <dependency>
            <groupId>io.springfoxgroupId>
            <artifactId>springfox-boot-starterartifactId>
            <version>3.0.0version>
        dependency>
        <dependency>
            <groupId>com.github.xiaoymingroupId>
            <artifactId>swagger-bootstrap-uiartifactId>
            <version>1.9.6version>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-configuration-processorartifactId>
            <optional>trueoptional>
        dependency>

        <dependency>
            <groupId>org.apache.commonsgroupId>
            <artifactId>commons-lang3artifactId>
            <version>3.10version>
        dependency>

swagger2访问地址 http://localhost/doc.html

swagger2 的配置类

@EnableSwagger2
@Configuration
public class SwaggerConfig {

    @Bean
    public Docket initDocket(Environment env) {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo()) .enable(true) .select()
                .apis(RequestHandlerSelectors
                        .withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any()) .build(); }

    private ApiInfo apiInfo() { return new ApiInfoBuilder()
            .title("图书管理系统") .description("管理书籍和读者信息,管理书籍,借阅和归还书籍")
            .contact(new Contact("coffeemao", null, "123456@qq.com "))
            .version("1.0") .build(); }
}

swagger3访问地址 http://localhost:8080/swagger-ui/index.html


@EnableOpenApi
@Configuration
public class SwaggerConfig {

    public Docket docket(){
        Docket docket = new Docket(DocumentationType.OAS_30);
        docket.apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.mao.book.controller"))
                .paths(PathSelectors.any()).build();
        return docket;
    }

    private ApiInfo apiInfo(){
        Contact contact = new Contact("作者 coffeemao", "作者www.baidu.com","123456@qq.com");
        ApiInfo apiInfo = new ApiInfo(
                "Swagger3接口文档",
                "SpringBoot 整合 Swagger3 生成接口文档!",
                "1.0.0",
                "termsOfServiceUrl",
                contact,
                "license",
                "licenseUrl",
                new ArrayList());
        return apiInfo;
    }
}

或者使用以下更为灵活的自定义配置类

SwaggerProperties 的属性类

@Component
@ConfigurationProperties("swagger")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class SwaggerProperties {

    private Boolean enable;

    private String applicationName;

    private String applicationVersion;

    private String applicationDescription;

    private String tryHost;
}

自定义的配置类

@EnableOpenApi
@Configuration
public class SwaggerConfiguration implements WebMvcConfigurer {
    private final SwaggerProperties swaggerProperties;

    public SwaggerConfiguration(SwaggerProperties swaggerProperties) {
        this.swaggerProperties = swaggerProperties;
    }

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.OAS_30).pathMapping("/")

                .enable(swaggerProperties.getEnable())

                .apiInfo(apiInfo())

                .host(swaggerProperties.getTryHost())

                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build()

                .protocols(newHashSet("https", "http"))

                .securitySchemes(securitySchemes())

                .securityContexts(securityContexts());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title(swaggerProperties.getApplicationName() + " Api Doc")
                .description(swaggerProperties.getApplicationDescription())
                .contact(new Contact("coffeemao", null, "123456@gmail.com"))
                .version("Application Version: " + swaggerProperties.getApplicationVersion() + ", Spring Boot Version: " + SpringBootVersion.getVersion())
                .build();
    }

    private List<SecurityScheme> securitySchemes() {
        ApiKey apiKey = new ApiKey("BASE_TOKEN", "token", In.HEADER.toValue());
        return Collections.singletonList(apiKey);
    }

    private List<SecurityContext> securityContexts() {
        return Collections.singletonList(
                SecurityContext.builder()
                        .securityReferences(Collections.singletonList(new SecurityReference("BASE_TOKEN", new AuthorizationScope[]{new AuthorizationScope("global", "")})))
                        .build()
        );
    }

    @SafeVarargs
    private final <T> Set<T> newHashSet(T... ts) {
        if (ts.length > 0) {
            return new LinkedHashSet<>(Arrays.asList(ts));
        }
        return null;
    }

    @SuppressWarnings("unchecked")
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        try {
            Field registrationsField = FieldUtils.getField(InterceptorRegistry.class, "registrations", true);
            List<InterceptorRegistration> registrations = (List<InterceptorRegistration>) ReflectionUtils.getField(registrationsField, registry);
            if (registrations != null) {
                for (InterceptorRegistration interceptorRegistration : registrations) {
                    interceptorRegistration
                            .excludePathPatterns("/swagger**/**")
                            .excludePathPatterns("/webjars/**")
                            .excludePathPatterns("/v3/**")
                            .excludePathPatterns("/doc.html");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

applicaton.xmlswagger3 进行了开启,应用的应用名字,应用程序的版本信息,描述信息,访问的地址等

spring:
  application:
    name: 图书管理系统
swagger:
  enable: true
  application-name: ${spring.application.name}
  application-version: 1.0
  application-description: swagger3.0 的图书管理文档
  try-host: http://localhost:${server.port}

swagger 文档的注解

  • @Api() 用在请求的类上,表示对类的说明,在 controller层的类上的注解

参数
tags:说明该类的作用,参数是个数组,可以填多个。
description = “用户基本信息操作”

  • @ApiOperation() 用于方法,表示一个http请求访问该方法的操作,在 controller层类的方法上的注解

参数
value=”方法的用途和作用”
notes=”方法的注意事项和备注”

  • @ApiModel() 在实体类模块下使用,说明该实体类的作用

参数
description=”描述实体的作用”

  • @ApiModelProperty() 在实体类的属性上使用,用于描述实体类的属性

参数
value=”用户名” 描述参数的意义
name=”name” 参数的变量名
required=true 参数是否必选

  • @ApiImplicitParams() controller 层的方法上多个参数的说明
  • @ApiImplicitParam() controller 层的方法上多个参数中每一个参数的说明

参数
name=”参数ming”
value=”参数说明”
dataType=”数据类型”
paramType=”query” 表示参数放在哪里
defaultValue=”参数的默认值”
required=”true” 表示参数是否必须传

  • @ApiParam() 用于方法,参数,字段说明 表示对参数的要求和说明

参数
name=”参数名称”
value=”参数的简要说明”
defaultValue=”参数默认值”
required=”true” 表示属性是否必填,默认为false

  • @ApiResponses() 用于请求的方法上,根据响应码表示不同响应

一个@ApiResponses包含多个@ApiResponse

  • @ApiResponse() 用在请求的方法上,表示不同的响应

参数
code=”404″ 表示响应码(int型),可自定义
message=”状态码对应的响应信息”

  • @ApiIgnore() 用于类或者方法上,不被显示在页面上
  • @Profile({"dev", "test"}) 用于配置类上,表示只对开发和测试环境有用

springboot 版本问题

出现问题是由于 springboot 的版本过高和 swagger 文档的不兼容

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.

2022-12-17 11:00:46.164 ERROR 8136 --- [  restartedMain] o.s.boot.SpringApplication               : Application run failed

org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException

项目中遇到的错误
    <!--标志是springboot的项目-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.2</version>
        <relativePath/>
    </parent>

降低版本

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.2</version>
        <relativePath/>
    </parent>

SQL 关键字异常

错误如下

2022-12-17 10:35:56.067 ERROR 10652 --- [p-nio-80-exec-5] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.jdbc.BadSqlGrammarException:
### Error updating database.  Cause: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc='12121'
        where
            id=1 and deleted=0' at line 7
### The error may exist in file [E:\Code\backproject\book\target\classes\mybatis\mapper\BookMapper.xml]
### The error may involve defaultParameterMap
### The error occurred while setting parameters
### SQL: update book         set             name=?,             image=?,             number=?,             price=?,             desc=?         where             id=? and deleted=0
### Cause: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc='12121'
        where
            id=1 and deleted=0' at line 7
; bad SQL grammar []; nested exception is java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc='12121'
        where
            id=1 and deleted=0' at line 7] with root cause

java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc='12121'
        where
            id=1 and deleted=0' at line 7

项目中遇到的错误

原因数据库的字段是 MySQL的关键字,这时候就需要加上(倒引号

<!--    SQL中的字段和关键字同名要使用 desc -->
    <update id="update">
        update book
        set
            name=#{name},
            image=#{image},
            number=#{number},
            price=#{price},
            desc=#{desc}
        where
            id=#{id} and deleted=0
    </update>

SQL 的关键字

https://www.cnblogs.com/langtianya/p/4968132.html

Apifox 的使用

下载安装 Apifoxhttps://www.apifox.cn/

使用导入数据

Apifox帮助文档

项目中遇到的错误

连接填写的是数据文档的 Url

swagger2文档注释的文档数据地址

http://localhost/v2/api-docs

swagger3文档注释的文档数据地址

http://localhost/v3/api-docs

集中版本管理

采用集中的版本信息管理,方便版本信息的统一更新


    <properties>
        <junit.version>4.12junit.version>
        <lombok.version>1.18.12lombok.version>
        <log4j.version>1.2.17log4j.version>
        <druid.version>1.2.5druid.version>
        <jdbc.version>8.0.25jdbc.version>
        <maven.compiler.source>11maven.compiler.source>
        <maven.compiler.target>11maven.compiler.target>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    properties>

版本控制所对应的依赖项目


        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>${junit.version}version>
            <scope>testscope>
        dependency>

        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <version>${lombok.version}version>
        dependency>

        <dependency>
            <groupId>log4jgroupId>
            <artifactId>log4jartifactId>
            <version>${log4j.version}version>
        dependency>

        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druid-spring-boot-starterartifactId>
            <version>${druid.version}version>
        dependency>

        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>${jdbc.version}version>
        dependency>

Original: https://blog.csdn.net/qq_46724069/article/details/128351194
Author: coffee_mao
Title: 项目中遇到的错误

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/724162/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球