Swagger接口文档的使用+常用注解

        Swagger是一款遵循 Restful 风格的接口文档开发神器,支持基于 API 自动生成接口文档接口文档始终与 API 保持同步,不再需要手动编写接口文档,并且采用全注解的方式,开发简单,代码侵入性低,对服务端开发的程序员来说非常方便,可以节约大量写接口文档的时间。除此之外,Swagger 生成的文档还支持在线测试,参数和格式都定好了,直接在界面上输入参数对应的值即可在线测试接口。

一、Spring整合Swagger:

(1)在 pom.xml 文件中添加 Swagger 的 maven 依赖:

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

(2)编写Swagger自定义配置类:

/** 
* 类说明 :自定义swagger配置信息
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
	
	@Bean
	 public Docket creatApi(){
	 return new Docket(DocumentationType.SWAGGER_2)
	  .apiInfo(apiInfo())
	  .select() //选择哪些路径和api会生成document
	  .apis(RequestHandlerSelectors.basePackage("com.zwp.controller"))//controller路径
	  //.apis(RequestHandlerSelectors.any())   //对所有api进行监控
	  .paths(PathSelectors.any())  //对所有路径进行监控
	  .build();
	 }
	
	//接口文档的一些基本信息
	private ApiInfo apiInfo() {
		return new ApiInfoBuilder()
				.title("springmvc+swagger整合")//文档主标题
				.description("test接口文档")//文档描述
				.version("1.0.0")//API的版本
				.termsOfServiceUrl("###")
				.license("LICENSE")
				.licenseUrl("###")
				.build();
	}
}

在 springmvc.xml 文件中配置创建对象:

<!-- 使用注解驱动:自动配置处理器映射器与处理器适配器 -->
<mvc:annotation-driven />
<!-- 注解方式:自动扫描该包 -->
<context:component-scan base-package="com.zwp.config" />

(3)在 springmvc.xml 中过滤掉 swagger-ui 的静态资源文件:

<mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/" />
<mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/" />

(4)在controller类添加swagger的注解:

//在类上面加@Api注解,表明该controller类需要被swagger自动生成文档
@Api(tags="UserController",description="user的控制层")
@Controller
@RequestMapping("/user")
public class UserController {
	
	@Autowired
	private UserService userService;

     //在方法上面添加@ApiOperation注解,表明该方法需要被swagger自动生成文档
	@ApiOperation(httpMethod="GET",value="接口标题:获取用户信息",notes="接口的notes说明:需要user的id")
	@RequestMapping(value="/getUserById/{userId}",method=RequestMethod.GET)
	public @ResponseBody User getUserById(@PathVariable Integer userId){
		return userService.getUserById(userId);
	}
	
}

(5)部署工程,访问路径:

格式:http://服务器ip:端口/项目名称//swagger-ui.html

例子:http://localhost:8080/ssm/swagger-ui.html

见到上面页面,表示整合成功。


二、swagger常用注解说明:

注解说明
@Api修饰controller类,标识这个类是swagger的资源 
@ApiOperation修饰controller的方法,表示一个http请求的操作
@ApiParam

修饰方法的参数,用于添加参数说明与是否必填等元数据

@ApiModel修饰对象类,表示对对象类进行说明,用于参数用实体类接收的场景 
@ApiModelProperty修饰对象类中的属性,对属性进行说明
@ApiIgnore()修饰类、方法、参数等,表示不显示在swagger文档中
@ApiImplicitParam用于方法,表示单独的请求参数 
@ApiImplicitParams用于方法,包含多个 @ApiImplicitParam

 1、@Api的使用说明:

修饰controller类,标识这个类是swagger的资源,属性说明:

  • tags:类的说明,但是tags如果有多个值,会生成多个list
  • value:也是类的说明,可以使用tags替代
@Api(value="用户controller",tags={"用户操作接口"})
@RestController
public class UserController {

}

 效果图: 

这里写图片描述

2、@ApiOperation的使用说明:

修饰controller的方法,表示一个http请求的操作,属性说明:

  • value:用于方法描述 
  • notes:用于提示内容 
  • tags:可以重新分组,视情况而用)

3、@ApiParam的使用说明:

修饰方法的参数,用于添加参数说明与是否必填等元数据,属性说明:

  • name:参数名 
  • value:参数说明 
  • required:是否必填
@Api(value="用户controller",tags={"用户操作接口"})
@RestController
public class UserController {
     @ApiOperation(value="获取用户信息",tags={"获取用户信息copy"},notes="注意问题点")
     @GetMapping("/getUserInfo")
     public User getUserInfo(@ApiParam(name="id",value="用户id",required=true) Long id,@ApiParam(name="username",value="用户名") String username) {
     // userService可忽略,是业务逻辑
      User user = userService.getUserInfo();

      return user;
  }
}

效果图: 

这里写图片描述

4、@ApiModel的使用说明:

修饰对象类,表示对对象类进行说明,用于参数用实体类接收的场景,属性说明:

  • value:表示对象名,可省略
  • description:描述,可省略

5、@ApiModelProperty的使用说明:

修饰对象类中的属性,对属性进行说明,属性说明:

  • value:字段说明
  • name:重写属性名字
  • dataType:重写属性类型
  • required:是否必填
  • example:举例说明
  • hidden:是否隐藏
@ApiModel(value="user对象",description="用户对象user")
public class User implements Serializable{
    private static final long serialVersionUID = 1L;
     @ApiModelProperty(value="用户名",name="username",example="xingguo")
     private String username;
     @ApiModelProperty(value="状态",name="state",required=true)
      private Integer state;
      private String password;
      private String nickName;
      private Integer isDeleted;

      @ApiModelProperty(value="id数组",hidden=true)
      private String[] ids;
      private List<String> idList;
}
  @ApiOperation("更改用户信息")
  @PostMapping("/updateUserInfo")
  public int updateUserInfo(@RequestBody @ApiParam(name="用户对象",value="传入json格式",required=true) User user){

     int num = userService.updateUserInfo(user);
     return num;
  }

效果图: 

这里写图片描述

6、@ApiIgnore的使用说明:

修饰类、方法、参数等,表示不显示在swagger文档中,比较简单, 这里不做举例

7、@ApiImplicitParam的使用说明:

用于方法,表示单独的请求参数

8、@ApiImplicitParams的使用说明:

用于方法,包含多个 @ApiImplicitParam,属性说明:

  • name:参数ming 
  • value:参数说明 
  • dataType:数据类型 
  • paramType:参数类型 
  • example:举例说明
  @ApiOperation("查询测试")
  @GetMapping("select")
  //@ApiImplicitParam(name="name",value="用户名",dataType="String", paramType = "query")
  @ApiImplicitParams({
  @ApiImplicitParam(name="name",value="用户名",dataType="string", paramType = "query",example="xingguo"),
  @ApiImplicitParam(name="id",value="用户id",dataType="long", paramType = "query")})
  public void select(){

  }

效果图: 

这里写图片描述

9、@ApiResponses与@ApiResponse使用说明:

这两个注解都表示对响应结果进行说明

10、@RequestMapping注解的推荐配置:

value、method、produces

示例:

    @ApiOperation("信息软删除")
    @ApiResponses({ @ApiResponse(code = CommonStatus.OK, message = "操作成功"),
            @ApiResponse(code = CommonStatus.EXCEPTION, message = "服务器内部异常"),
            @ApiResponse(code = CommonStatus.FORBIDDEN, message = "权限不足") })
    @ApiImplicitParams({ @ApiImplicitParam(paramType = "query", dataType = "Long", name = "id", value = "信息id", required = true) })
    @RequestMapping(value = "/remove.json", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RestfulProtocol remove(Long id) {

  • 2
    点赞
  • 49
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

张维鹏

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值