Swagger 简介与使用

POM 依赖

<!-- 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.9.2</version>
</dependency>

<!-- 上面的 Swagger UI 是原生的 Swagger 页面,比较繁杂。我们一般替换为以下 UI -->
<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>swagger-bootstrap-ui</artifactId>
    <version>1.9.5</version>
</dependency>

配置

@Configuration
@EnableSwagger2
public class Swagger2Config {

    @Bean
    public Docket coreApiConfig() {
        return new Docket(DocumentationType.SWAGGER_2)
                // API 的基本信息
                .apiInfo(apiInfo())
                // select() 会返回一个 ApiSelectorBuilder 实例,用来控制哪些接口暴露给 Swagger 来展现
                .select()
                // 指定扫描接口的方式,RequestHandlerSelectors 下共有五种方式可选,这里使用在类上添加 @Api 注解的方式
                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
                // 指定扫描接口的路径,PathSelectors 下共有四种方式可选,这里使用全扫方式
                .paths(PathSelectors.any())
                .build();
    }

    /**
     * 基本的配置信息,会显示在 api 文档上
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("study-main——api文档")
                .version("1.0.0")
                // 服务条款 URL
                .termsOfServiceUrl("http://localhost:8080/helloWorld/quickStart")
                // 我的主页和邮箱
                .contact(new Contact("夏博阳", "http://baidu.com", "1947304419@qq.com"))
                .build();
    }
}

代码

@Data
@NoArgsConstructor
@AllArgsConstructor
@ApiModel
public class User {
    @ApiModelProperty(value = "用户ID", name = "id", example = "1")
    private Integer userId;

    @ApiModelProperty(value = "用户名称", hidden = true)
    private String userName;
}

@Api
@RestController
@RequestMapping("/helloWorld")
public class HelloWorldController {

    @ApiOperation("快速开始")
    @RequestMapping("/quickStart")
    public User quickStart(@ApiParam(name = "user", value = "登陆人信息"
    	, required = true) @RequestBody User user) {
        return user;
    }
}

此时我们就可以访问 http://localhost:8080/swagger-ui.html 进入 Swagger 页面,其中就会显示接口信息和实体类信息。替换了 UI 依赖包的话就访问 http://localhost:8080/doc.html

注解介绍

@Api:用于 Controller ,标识为 swagger 资源
    
@ApiIgnore:用于 Controller ,忽略该 Controller ,即不做扫描
    
@ApiOperation:用于方法,描述该方法
    
@ApiParam:用于入参,描述该入参
    
@ApiModel:用于实体类,标识为 Swagger 资源
    
@ApiModelProperty:结合 @ApiModel 使用,用在属性上对属性进行说明
    
@ApiImplicitParams:用于方法,用来包含多个 @ApiImplicitParam
    
@ApiImplicitParam:用于方法,作用与 @ApiParam 相同,都是描述入参
    
@ApiResponses:用于方法,用来包含多个 @ApiResponse
    
@ApiResponse:用于方法,描述出参
    
@ApiError:用于方法,描述接口错误所返回的信息
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值