项目中遇到的错误

swagger2 和 swagger3

swagger2swagger3 需要导入的依赖

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.9.6</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <!-- commons-lang3-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.10</version>
        </dependency>

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

swagger2 的配置类

@EnableSwagger2
@Configuration
public class SwaggerConfig {
    /**
     * 设置要暴露接口文档的配置环境
     * @param env 环境
     * @return Docket
     */
    @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

// 开启 OpenApi
@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 {
    /**
     * 是否开启swagger,生产环境一般关闭,所以这里定义一个变量
     */
    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("/")

                // 定义是否开启swagger,false为关闭,可以通过变量控制
                .enable(swaggerProperties.getEnable())

                // 将api的元信息设置为包含在json ResourceListing响应中。
                .apiInfo(apiInfo())

                // 接口调试地址
                .host(swaggerProperties.getTryHost())

                // 选择哪些接口作为swagger的doc发布
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build()

                // 支持的通讯协议集合
                .protocols(newHashSet("https", "http"))

                // 授权信息设置,必要的header token等认证信息
                .securitySchemes(securitySchemes())

                // 授权信息全局应用
                .securityContexts(securityContexts());
    }

    /**
     * API 页面上半部分展示信息
     */
    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;
    }

    /**
     * 通用拦截器排除swagger设置,所有拦截器都会自动加swagger相关的资源排除信息
     */
    @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.12</junit.version>
        <lombok.version>1.18.12</lombok.version>
        <log4j.version>1.2.17</log4j.version>
        <druid.version>1.2.5</druid.version>
        <jdbc.version>8.0.25</jdbc.version>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

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

		<!-- junit 单元测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <!-- lombok 脚手架工具 -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
        </dependency>
        <!-- log4j日志信息 -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
        </dependency>
        <!-- alibaba的druid数据源 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>${druid.version}</version>
        </dependency>
        <!-- 数据库连接驱动器 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${jdbc.version}</version>
        </dependency>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值