Swagger的配置与使用

swagger

前言

学习

1.swagger前期准备

搜索springfox-swag引入两个jar包,springfox-swagger2springfox-swagger-ui

<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

2.简单测试

创建config包

package com.example.demo.config;

import org.springframework.context.annotation.Configuration;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2     //开启swagger2
public class SwaggerConfig {
}

创建controller包

package com.example.demo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class testController {
    @GetMapping("/index")
    public String index(){
        return "index";
    }
}

运行程序

如果出现这个错误Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException在配置文件中添加spring.mvc.pathmatch.matching-strategy=ANT_PATH_MATCHER

访问http://localhost:8080/swagger-ui.html,注意换成你自己的端口号

image

3.配置config

package com.example.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;

@Configuration
@EnableSwagger2     //开启swagger2
public class SwaggerConfig {

    // 配置Swagger的Docker的bean实例
    @Bean
    public Docket docket(){
        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo());
    }

    // 配置swagger的信息apiInfo
    private ApiInfo apiInfo(){
        // 作者信息
        Contact contact = new Contact("芊嵛", "https://www.cnblogs.com/qy-blog", "2459689942@qq.com");
        return new ApiInfo(
            // 标题
            "芊嵛的SwaggerAPI文档",
            // 描述
            "少年意气",
            // 版本
            "1.0",
            // 服务条款网址
            "https://www.cnblogs.com/qy-blog",
            contact,
            //许可
            "Apache 2.0",
            // 许可链接
            "http://www.apache.org/licenses/LICENSE-2.0",
            new ArrayList()
        );
    }
}

image

明天继续。。。

posted @ 2024-04-29 18:19  芊嵛  阅读(36)  评论(0编辑  收藏  举报