Spring Boot中Swagger的使用及注解说明

什么是Swagger,有什么作用?

Swagger 是基于(OpenAPI 规范——RESTful API 设计的行业标准)开源的针对API 开发所设计的接口文档设计及记录。 以及使用 Rest API。

特别适用于互联网项目,对于前后端分离Rest API 文档共享。 1、Swagger 根据代码自动生成 API 文档,接口代码变更文档同步更新,保证了及时性。 2、Swagger UI 是一个可视化界面根据简单的注解可以给接口添加不同备注,同时可以进行接口的调试,检查。 3、同时可在线导入规范文档和部署Swagger UI。 4、Swagger Codegen可生成服务端或者客户端代码且支持多种语言,同时可以成html接口文档等。

web项目添加Swagger依赖

1、在pom.xml中添加dependency

<!-- swagger-springmvc start -->
		<!-- 添加 Swagger 依赖 -->
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>2.9.2</version>
		</dependency>
		<!-- 添加 Swagger UI 依赖 -->
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger-ui</artifactId>
			<version>2.8.0</version>
		</dependency>
		<!-- swagger-springmvc end -->

服务启动类上,添加swagger启动注解

2、添加swagger启动注解

/**
 * 注解:@EnableSwagger2
 * 说明:开启Swagger2,
 * 服务启动后再浏览器访问http://localhost:8080/swagger-ui.html
 */

@SpringBootApplication
@EnableSwagger2
public class SwaggerDemoApplication {
          
   
	public static void main(String[] args) {
          
   
		SpringApplication.run(SwaggerDemoApplication.class, args);
	}
}

3、在浏览器中输入http://localhost:8080/swagger-ui.html验证swaggerUI了。

成功!!!

添加API文档描述

接口文档摘要说明设置,设置需要暴露的接口,默认全暴露

验证Swagger是否成功

添加注解说明

1、@Api、@ApiOperation、@ApiParam

@RestController
@RequestMapping(value = "/account")
@Api(tags = "账号相关接口",description = "账号查询与修改")
public class AccountController {
          
   

    @Autowired
    private AccountService accountService;

    @RequestMapping(value = "/find")
    @ApiOperation(value = "账号查询",httpMethod ="GET", response = Account.class,notes = "account find")
    public Account getAccountById(Long id){
          
   
      return accountService.getAccountById(id);
    }

    @RequestMapping(value = "/update",method = RequestMethod.POST)
    @ApiOperation(value = "修改年龄",httpMethod ="GET", response = String.class,notes = "modify age")
    public Account updateAccountByName(Long accountId,Long age){
          
   
        Account accont = accountService.getAccountById(accountId);
        accont.setAge(age);
        return accountService.update(accont);
    }
}

验证添加注解后效果

swagger常用注解说明

一、用于Controller类上

1、@Api

属性: tags (Stirng) 标签。 description(String)类描述。

二、用于方法上

1、@ApiIgnore 屏蔽某个接口方法使其不暴露

2、@ApiOperation 用在方法上,说明方法的作用 属性: value(String)方法描述 httpMethod(String)接口请求类型 response(Class<?>)返回类型 notes(String)接口发布说明 tags String[] 标签

3、@ApiParam 用在方法内,参数校验及说明 属性: name(String)参数名 required(boolean)参数是否必须传 value(object)参数的意思 defaultValue(object)参数的默认值

三、作用在实体类上

1、@ApiModelProperty:描述一个model的属性 属性: value (String)字段说明。 name (String)重写字段名称。 dataType(String)重写字段类型。 required (boolean)是否必填。 example (String)举例说明。 hidden (boolean)是否在文档中隐藏该字段。 allowEmptyValue(boolean)是否允许为空。 allowableValues (String)字段允许的值,传入值不一致时提示

使用Swagger调用接口测试

成功!!!下面可进行其他接口测试啦,开始你的工作吧

经验分享 程序员 微信小程序 职场和发展