Swagger2用法整理

一、集成Swagger2

1.1、引入pom依赖

引入springfox相关依赖包

		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>2.9.2</version>
		</dependency>
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger-ui</artifactId>
			<version>2.9.2</version>
		</dependency>

1.2、开启注解

在启动类中开启@EnableSwagger2注解

package com.example.swagger2;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@EnableSwagger2
@SpringBootApplication
public class Swagger2Application {

	public static void main(String[] args) {
		SpringApplication.run(Swagger2Application.class, args);
	}

}

1.3、编写控制器

package com.example.swagger2.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@Controller
public class TestController {

    @GetMapping("/test")
    @ResponseBody
    public Map<String, Object> getMsg() {
        Map<String, Object> map = new HashMap<>();
        map.put("result", "response msg");
        return map;
    }
}

1.4、访问API界面

启动服务后,访问地址http://ip:port/swagger-ui.html,即可见swagger主页
在这里插入图片描述

二、常用配置

2.1、配置基本信息

创建SwaggerConfig配置类,并填充对应平台信息

package com.example.swagger2.config;

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

@Configuration
public class SwaggerConfig {
    @Bean
    public Docket getDocket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(swaggerDemoApiInfo()) .select() .build();
    }

    private ApiInfo swaggerDemoApiInfo(){
        return new ApiInfoBuilder()
                .contact(new Contact("xxx平台", "http://www.xxxxx.com", "xxx@163.com"))
        .title("Swagger标题")  //文档标题
        .description("Swagger描述信息")   //文档描述
        .version("1.0.0") .build();  //文档版本
    }

}

在这里插入图片描述

2.2、扫描包路径设置

只扫描com.example.swagger2.controller路径下的方法

 @Bean
    public Docket getDocket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(swaggerDemoApiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.swagger2.controller"))
                .build();
    }

2.3、设置不需要生成接口文档的方法(自定义注解)

定义一个方法级别的注解,策略为运行时解析

package com.example.swagger2.config;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface NotIncludeSwagger {
}

(not(withMethodAnnotation(NotIncludeSwagger.class)))表示方法级别注解不执行

...

import static com.google.common.base.Predicates.not;
import static springfox.documentation.builders.RequestHandlerSelectors.withMethodAnnotation;


@Configuration
public class SwaggerConfig {
    @Bean
    public Docket getDocket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(swaggerDemoApiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.swagger2.controller"))
                .apis((not(withMethodAnnotation(NotIncludeSwagger.class))))
                .build();
    }

 ....

在对应方法上使用@NotIncludeSwagger即可,该方法不会显示在swagger接口文档页面

	@NotIncludeSwagger
    @GetMapping("/test")
    @ResponseBody
    public Map<String, Object> getMsg() {
        Map<String, Object> map = new HashMap<>();
        map.put("result", "response msg");
        return map;
    }

2.4、设置范围

使用paths()方法,可以通过正则方式指定需要匹配到的方法;
定义2个方法,分别以/test/hello访问路径开头

@GetMapping("/test/getMsg")
    @ResponseBody
    public Map<String, Object> getMsg() {
        Map<String, Object> map = new HashMap<>();
        map.put("result", "response msg");
        return map;
    }

    @PostMapping("/hello/getMsg2")
    @ResponseBody
    public Map<String, Object> getMsg2() {
        Map<String, Object> map = new HashMap<>();
        map.put("result", "response msg");
        return map;
    }

指定访问所有/test路径开头的方法

...
 .apis((not(withMethodAnnotation(NotIncludeSwagger.class))))
                .paths(PathSelectors.regex("/test/.*"))
                .build();

指定多个时使用or方法

.paths(or(PathSelectors.regex("/test/.*"), PathSelectors.regex("/hello/.*")))

三、常用注解

3.1、Api

@Api 是类上注解,控制整个类生成接口信息的内容;
tags:类的名称。可以有多个值,多个值表示多个副本;
description:描述,已过时;

@Api(tags = {"类名称信息"},description = "类描述信息")
public class TestController {}

3.2、ApiOperation

@ApiOperation 写在方法上,对方法进行总体描述;
value:接口描述;
notes:提示信息;

	@ApiOperation(value="接口描述",notes = "接口提示信息")
    @PostMapping("/test/getMovieInfo")
    @ResponseBody
    public MovieInfo getMovieInfo() {
        MovieInfo info = new MovieInfo();
        info.setName("当幸福来敲门");
        info.setRole("威尔史密斯");
        return info;
    }

3.3、ApiParam

@ApiParam 写在方法参数前面。用于对参数进行描述或说明是否 为必添项等说明;
name:参数名称;
value:参数描述;
required:是否必传字段;

public MovieInfo getMovieInfo(@ApiParam(value="电影名称",required = true) String name) {}

3.4、ApiModel

@ApiModel 是类上注解,主要应用 Model,也就是说这个注解一 般都是写在实体类上;
value:实体对象名称;
description:实体对象描述信息;

@ApiModel(value = "电影实体对象",description = "电影实体对象描述")
public class MovieInfo {

    private Long id;    //主键
    private String name;    //电影名称
    private String role;    //主演
    private String area;    //地区(大陆、香港、美国)
	...
}

3.5、ApiModelProperty

@ApiModelProperty 可以用在方法或属性上。用于当对象作为参 数时定义这个字段的内容;
value:描述;
name:重写属性名;
required:是否是必须的;
example:示例内容;
hidden:是否隐藏;

	@ApiModelProperty(value = "电影名称",name = "name",required = true, example = "当幸福来敲门")
    private String name;    //电影名称

3.6、ApiIgnore

@ApiIgnore 用于方法或类或参数上,表示这个方法或类被忽略,和上面自定义的@NotIncludeSwagger 注解功能相似;

3.7、ApiImplicitParam

@ApiImplicitParam 用在方法上,表示单独的请求参数,总体功能 和@ApiParam 类似;
name:属性名;
value:描述;
required:是否是必须;
paramType:属性类型;
dataType:数据类型;

	@ApiImplicitParam(name = "name",value = "电影名称",required = true,paramType = "query",dataType = "string")
    public MovieInfo getMovieInfo( String name) {}
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值