springboot-swagger

springboot集成swagger3

1、swagger常用注解

swagger提供了一些配置用来描述接口,下面是一些常用的注解,必须掌握;

@Api

@Api:用在请求的类上,表示对类的说明
    tags="说明该类的作用,可以在UI界面上看到的注解"
    value="该参数没什么意义,在UI界面上也看到,所以不需要配置"

@ApiOperation

@ApiOperation:用在请求的方法上,说明方法的用途、作用
    value="说明方法的用途、作用"
    notes="方法的备注说明"

@ApiImplicitParams

@ApiImplicitParams:用在请求的方法上,表示一组参数说明
    @ApiImplicitParam:用在@ApiImplicitParams注解中,指定一个请求参数的各个方面
        name:参数名
        value:参数的汉字说明、解释
        required:参数是否必须传
        paramType:参数放在哪个地方
        	· header --> 请求参数的获取:@RequestHeader
        	· query --> 请求参数的获取:@RequestParam
       	 	· path(用于restful接口)--> 请求参数的获取:@PathVariable
        	· div(不常用)
        	· form(不常用)
        dataType:参数类型,默认String,其它值dataType="Integer"
        defaultValue:参数的默认值

@ApiResponses

@ApiResponses:用在请求的方法上,表示一组响应
    @ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息
        code:数字,例如400
        message:信息,例如"请求参数没填好"
        response:抛出异常的类

@ApiModel

@ApiModel:用于响应类上,表示一个返回响应数据的信息(这种一般用在post创建的时候,使用@RequestBody这样的场景,请求参数无法使用@ApiImplicitParam注解进行描述的时候

@ApiModelProperty

@ApiModelProperty:用在属性上,描述响应类的属性
2、swagger3快速开始

使用springboot2.6以下版本进行测试 要不然会报错

2.1 springboot快速构建

添加一个spring web即可

2.2 加下Swagger依赖:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>

这里用的是 springfox,Swagger 可以看作是一个遵循了 OpenAPI 规范的一项技术,而 springfox 则是这项技术的具体实现。

2.3 开启Swagger3

在 Spring Boot 的启动类添加 @EnableOpenApi 注解,开启 Swagger支持;

@EnableOpenApi
@SpringBootApplication
public class SwaggerTestApplication {
    public static void main(String[] args) {
        SpringApplication.run(SwaggerTestApplication.class, args);
    }
}
2.4 添加一个控制类
@RestController
public class HelloWorldController {
    @RequestMapping("/helloWorld")
    public String helloWorld(){
        return "helloWorld";
    }
}
2.5 访问swagger-ui 查看接口文档

浏览器访问:http://localhost:8080/swagger-ui/

2.6 常用注解在类中使用
@Api(tags="helloWorld类测试")
@RestController
public class HelloWorldController {


    @ApiOperation("测试方法")
    @RequestMapping(value = "/helloWorld",method = RequestMethod.GET)
    public String helloWorld(){
        return "helloWorld";
    }


    /**
     * 查询
     * @param name
     * @param age
     * @return
     */
    @PostMapping("/search")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name",value = "姓名",required = true,paramType
                    = "query"),
            @ApiImplicitParam(name = "age",value = "年龄",required = true,paramType =
                    "query",dataType = "Integer")
    })

    @ApiOperation("测试查询")
    public String search(String name,Integer age){
        return name+":"+age;
    }


    /**
     * 添加测试
     * @param user
     * @return
     */
    @PostMapping("/add")
    @ApiOperation("测试添加")
    public String add(User user){
        return user.getName()+":"+user.getAge();
    }


    @GetMapping("/user/{id}")
    @ApiOperation("根据ID获取用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "用户编号",required = true,paramType
                    = "path")
    })
    @ApiResponses({
            @ApiResponse(code=408,message="指定业务得报错信息,返回客户端"),
            @ApiResponse(code=400,message="请求参数没填好"),
            @ApiResponse(code=404,message="请求路径没有或页面跳转路径不对")
    })
    public User load(@PathVariable("id") Integer id){
        return new User(id,"jack",32);
    }

}

User类

@ApiModel("用户信息实体")
public class User {


    @ApiModelProperty("编号")
    private Integer id;
    @ApiModelProperty("姓名")
    private String name;
    @ApiModelProperty("年龄")
    private Integer age;


    public User() {
    }
    public User(Integer id,String name, Integer age) {
        this.id=id;
        this.name = name;
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
3、Swagger3 API信息配置

在这里插入图片描述

修改API信息默认配置 重写 ApiInfo 实现,以及重写 Docket 实现并且设置apiInfo

@Configuration
public class Swagger3Config {
    /**
* 配置swagger的Docket bean
* @return
*/
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.OAS_30) // 指定swagger3.0版本
            .apiInfo(createApiInfo());
    }
    
    /**
* 配置swagger的ApiInfo bean
* @return
*/
    @Bean
    public ApiInfo createApiInfo(){
        return new ApiInfo("Java1234 Swagger"
                           ,"Java1234 Api Documentation"
                           ,"3.0"
                           ,"http://www.java1234.vip"
                           ,new Contact("小锋", "http://www.java1234.vip",
                                        "caofeng2012@126.com")
                           ,"Apache 2.0"
                           ,"http://www.apache.org/licenses/LICENSE-2.0"
                           ,new ArrayList());
    }
}
4、Swagger3 Docket 开关&过滤&分组 配置详解

我们可以通过设置Docket,可以配置很多功能,比如是否开启swagger,过滤,分组等

4.1 开关设置enable

一般情况,我们只有在开发环境才会用到swagger,正式环境需要关闭swagger,一个是安全问题,还有一个是用了swagger会影响系统运行速度;
我们通过设置Docket对象的enable即可;

/**
* 配置swagger的Docket bean
* @return
*/
@Bean
public Docket createRestApi() {
    return new Docket(DocumentationType.OAS_30) // 指定swagger3.0版本
        .enable(false) // 开关
        .apiInfo(createApiInfo());
}

重启项目 就看不到这个swagger

4.2 设置过滤

有些情况,我们需要指定固定包路径下的类生成API,或者根据前端用户路径请求过滤;使用过滤,必须先调用 select 方法;
通过apis方法, basePackage 可以根据包路径来生成特定类的API,any 方法是默认所有都有效, none 方法都无效;
withClassAnnotation 根据类注解, withMethodAnnotation 是根据方法注解;
一般我们用的是 basePackage 方法;

/**
* 配置swagger的Docket bean
* @return
*/
@Bean
public Docket createRestApi() {
    return new Docket(DocumentationType.OAS_30) // 指定swagger3.0版本
        .enable(true) // 开关
        .select()
        .apis(RequestHandlerSelectors.basePackage("com.java1234.controller")) // 指定扫描
        的包 常用方式
        .build()
        .apiInfo(createApiInfo());
}

最后要加 build() 方法;
类似的还有一个根据请求路径的 paths 方法;
一般用 ant 匹配路径;
any 是匹配任意路径, none 是都不匹配, regex 是正则匹配;

/**
* 配置swagger的Docket bean
* @return
*/
@Bean
public Docket createRestApi() {
    return new Docket(DocumentationType.OAS_30) // 指定swagger3.0版本
        .enable(true) // 开关
        .select()
        .paths(PathSelectors.ant("/java1234/**")) // 匹配 /java1234/**请求路径
        .build()
        .apiInfo(createApiInfo());
}
4.3 设置分组 页面显示后右上角的分组

在实际项目开发中,把复杂项目划分多模块给多个小组或者多个人负责开发,所以每个小组或者个人要实现自己的分组,方便查找到API接口开发负责人,沟通和处理问题;
我们通过 groupName 方法可以设置组名;

@Configuration
public class Swagger3Config {
    /**
* 配置swagger的Docket bean
* @return
*/
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.OAS_30) // 指定swagger3.0版本
            .groupName("开发组001")
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.java1234.controller.one")) // 指
            定扫描的包 常用方式
            .build()
            .apiInfo(createApiInfo());
    }
    
    /**
* 配置swagger的Docket bean
* @return
*/
    @Bean
    public Docket createRestApi2() {
        return new Docket(DocumentationType.OAS_30) // 指定swagger3.0版本
            .groupName("开发组002")
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.java1234.controller.two")) // 指
            定扫描的包 常用方式
            .build()
            .apiInfo(createApiInfo2());
    }
    
    俩个分组后的信息///
    
    /**
* 配置swagger的ApiInfo bean
* @return
*/
    @Bean
    public ApiInfo createApiInfo(){
        return new ApiInfo("Java1234 Swagger"
                           ,"Java1234 Api Documentation"
                           ,"3.0"
                           ,"http://www.java1234.vip"
                           ,new Contact("小锋", "http://www.java1234.vip",
                                        "caofeng2012@126.com")
                           ,"Apache 2.0"
                           ,"http://www.apache.org/licenses/LICENSE-2.0"
                           ,new ArrayList());
    }
    /**
* 配置swagger的ApiInfo bean
* @return
*/
    @Bean
    public ApiInfo createApiInfo2(){
        return new ApiInfo("Java1234 Swagger"
                           ,"Java1234 Api Documentation"
                           ,"3.0"
                           ,"http://www.java1234.vip"
                           ,new Contact("小丽", "http://www.java1234.vip",
                                        "caofeng2012@126.com")
                           ,"Apache 2.0"
                           ,"http://www.apache.org/licenses/LICENSE-2.0"
                           ,new ArrayList());
    }
}
5 拓展:其他皮肤
5.1 bootstrap-ui

访问 http://localhost:8080/doc.html

<!-- 引入swagger-bootstrap-ui包 /doc.html-->
<dependency>
   <groupId>com.github.xiaoymin</groupId>
   <artifactId>swagger-bootstrap-ui</artifactId>
   <version>1.9.1</version>
</dependency>
5.2 Layui-ui

访问 http://localhost:8080/docs.html

<!-- 引入swagger-ui-layer包 /docs.html-->
<dependency>
   <groupId>com.github.caspar-chen</groupId>
   <artifactId>swagger-ui-layer</artifactId>
   <version>1.1.3</version>
</dependency>
5.3 mg-ui

访问 http://localhost:8080/document.html

<!-- 引入swagger-ui-layer包 /document.html-->
<dependency>
   <groupId>com.zyplayer</groupId>
   <artifactId>swagger-mg-ui</artifactId>
   <version>1.0.6</version>
</dependency>
6 springboot2.6以上版本配置swagger出现问题

解决方法

https://blog.csdn.net/weixin_44075369/article/details/121573796
7 springboot与swagger2.0配置

使用的是狂神的教学

狂神讲解的比较清晰

https://mp.weixin.qq.com/s?__biz=Mzg2NTAzMTExNg==&mid=2247483909&idx=1&sn=201ee629b9ce3b9276a263e18812e607&scene=19#wechat_redirect
8 swagger 全局配置token

这样就可以只输入一次token就访问

 @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.OAS_30) // 指定swagger3.0版本
                .apiInfo(createApiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.itheima.controller"))
                .paths(PathSelectors.any())
                .build()
                .securitySchemes(unifiedAuth());
    }
// 配置
 private static List<SecurityScheme> unifiedAuth() {
        List<SecurityScheme> arrayList = new ArrayList();
        arrayList.add(new ApiKey("app-type", "app-type", "header"));
        arrayList.add(new ApiKey("app-token", "app-token", "header"));
        return arrayList;
    }

等待更新

lectors.basePackage(“com.example.itheima.controller”))
.paths(PathSelectors.any())
.build()
.securitySchemes(unifiedAuth());
}
// 配置
private static List unifiedAuth() {
List arrayList = new ArrayList();
arrayList.add(new ApiKey(“app-type”, “app-type”, “header”));
arrayList.add(new ApiKey(“app-token”, “app-token”, “header”));
return arrayList;
}

9 knife4j的使用

资料来源

https://baijiahao.baidu.com/s?id=1699829803518284149

导包

 <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>knife4j-spring-boot-starter</artifactId>
            <version>2.0.2</version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>29.0-jre</version>
        </dependency>
        

配置

@Configuration
@EnableSwagger2
public class Knife4jConfig {

    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("ltd.newbee.mall.controller"))
                .paths(PathSelectors.any())
                .build();

    }

    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("Springboot项目 后台服务API接口文档")
                .description("使用knife4j 搭建的后台服务API接口文档")
                .termsOfServiceUrl("http://localhost:28089")
                .contact("xuzebin")
                .version("1.0.0")
                .build();
    }
}

放行资源

@MapperScan("ltd.newbee.mall.dao")
//@EnableOpenApi
@ConditionalOnClass(SpringfoxWebMvcConfiguration.class)
@SpringBootApplication
public class NewBeeMallApplication implements WebMvcConfigurer {
    public static void main(String[] args) {
        SpringApplication.run(NewBeeMallApplication.class, args);
    }

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

等待更新

如何将token jwt 与swagger在实战中结合起来

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值