springmvc+swagger整合、swagger常用注解详细说明

Swagger 是一款RESTFUL接口的文档在线自动生成+功能测试功能软件。 Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。Swagger 让部署管理和使用功能强大的API从未如此简单。

 

一、springmvc+swagger的整合:

(1)在pom.xml中添加swagger的jar包依赖:

<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的类中进行相关的配置:

//需要在类上面加@Api注解,表明该controller类需要被swagger自动生成文档
@Controller
@RequestMapping("/user")
@Api(tags="UserController",description="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常用注解说明: 

该部分的内容转自:https://blog.csdn.net/u014231523/article/details/76522486
@Api()用于类; 
表示标识这个类是swagger的资源 
@ApiOperation()用于方法; 
表示一个http请求的操作 
@ApiParam()用于方法,参数,字段说明; 
表示对参数的添加元数据(说明或是否必填等) 
@ApiModel()用于类 
表示对类进行说明,用于参数用实体类接收 
@ApiModelProperty()用于方法,字段 
表示对model属性的说明或者数据操作更改 
@ApiIgnore()用于类,方法,方法参数 
表示这个方法或者类被忽略 
@ApiImplicitParam() 用于方法 
表示单独的请求参数 
@ApiImplicitParams() 用于方法,包含多个 @ApiImplicitParam

具体使用举例说明: 
@Api() 
用于类;表示标识这个类是swagger的资源 
tags–表示说明 
value–也是说明,可以使用tags替代 
但是tags如果有多个值,会生成多个list

@Api(value="用户controller",tags={"用户操作接口"})
@RestController
public class UserController {

}

效果图: 
这里写图片描述

@ApiOperation() 用于方法;表示一个http请求的操作 
value用于方法描述 
notes用于提示内容 
tags可以重新分组(视情况而用) 
@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;
  }
}

效果图: 
这里写图片描述

@ApiModel()用于类 ;表示对类进行说明,用于参数用实体类接收 
value–表示对象名 
description–描述 
都可省略 
@ApiModelProperty()用于方法,字段; 表示对model属性的说明或者数据操作更改 
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;
     //省略get/set
}
  @ApiOperation("更改用户信息")
  @PostMapping("/updateUserInfo")
  public int updateUserInfo(@RequestBody @ApiParam(name="用户对象",value="传入json格式",required=true) User user){

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

效果图: 
这里写图片描述

这里写图片描述

@ApiIgnore()用于类或者方法上,可以不被swagger显示在页面上 
比较简单, 这里不做举例

@ApiImplicitParam() 用于方法 
表示单独的请求参数 
@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(){

  }

效果图: 
这里写图片描述

三、swaggerAPI详细说明:

该部分内容转自:https://blog.csdn.net/xupeng874395012/article/details/68946676

注释汇总:

作用范围 API 使用位置
对象属性 @ApiModelProperty 用在出入参数对象的字段上
协议集描述 @Api 用于controller类上
协议描述 @ApiOperation 用在controller的方法上
Response集 @ApiResponses 用在controller的方法上
Response @ApiResponse 用在 @ApiResponses里边
非对象参数集 @ApiImplicitParams 用在controller的方法上
非对象参数描述 @ApiImplicitParam 用在@ApiImplicitParams的方法里边
描述返回对象的意义 @ApiModel 用在返回对象类上

@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) {
    @ApiModelProperty(value = "标题")
    private String  title;

@ApiImplicitParam

属性 取值 作用
paramType   查询参数类型
  path 以地址的形式提交数据
  query 直接跟参数完成自动映射赋值
  body 以流的形式提交 仅支持POST
  header 参数在request headers 里边提交
  form 以form表单的形式提交 仅支持POST
dataType   参数的数据类型 只作为标志说明,并没有实际验证
  Long  
  String  
name   接收参数名
value   接收参数的意义描述
required   参数是否必填
  true 必填
  false 非必填
defaultValue   默认值

paramType 示例详解

path

 @RequestMapping(value = "/findById1/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)

 @PathVariable(name = "id") Long id

body

  @ApiImplicitParams({ @ApiImplicitParam(paramType = "body", dataType = "MessageParam", name = "param", value = "信息参数", required = true) })
  @RequestMapping(value = "/findById3", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)

  @RequestBody MessageParam param

  提交的参数是这个对象的一个json,然后会自动解析到对应的字段上去,也可以通过流的形式接收当前的请求数据,但是这个和上面的接收方式仅能使用一个(用@RequestBody之后流就会关闭了)

header

  @ApiImplicitParams({ @ApiImplicitParam(paramType = "header", dataType = "Long", name = "id", value = "信息id", required = true) }) 

   String idstr = request.getHeader("id");
        if (StringUtils.isNumeric(idstr)) {
            id = Long.parseLong(idstr);
        }

Form

@ApiImplicitParams({ @ApiImplicitParam(paramType = "form", dataType = "Long", name = "id", value = "信息id", required = true) })
 @RequestMapping(value = "/findById5", method = RequestMethod.POST, produces = MediaType.APPLICATION_JS

猜你喜欢

转载自blog.csdn.net/a745233700/article/details/81107012