Spring搭建swagger

1.导入依赖

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

2.配置

/**
 * swagger配置类,默认访问路径 <a href="http://localhost:8080/swagger-ui.html">...</a>
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket createRestApi(){
        ParameterBuilder tokenPar = new ParameterBuilder();
        List<Parameter> pars = new ArrayList<>();
        tokenPar.name("Authorization").description("令牌").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
        pars.add(tokenPar.build());
        return new Docket(DocumentationType.SWAGGER_2)
        .apiInfo(apiInfo())
        .select()
        .apis(RequestHandlerSelectors.basePackage("com.foda.a8.controller"))    // 对指定目录下文件进行监控
        .paths(PathSelectors.any())
        .build()
        .globalOperationParameters(pars);
    }

    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
        .title("A8 Doc")
        .description("This is a restful api document of A8.")
        .version("1.0")
        .build();
    }
}

如果是使用springfox-swagger-ui,启动项目后的api文档访问路径是 /swagger-ui.html

swagger-bootstrap-ui

swagger-bootstrap-ui是springfox-swagger的增强UI实现,我个人更推荐使用这个ui,api文档结构更加清晰,在线调试也很方便

<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>swagger-bootstrap-ui</artifactId>
    <version>${swagger.bootstrap.ui.version}</version>
</dependency>

访问的url为 /doc.html

Swagger分组

Swagger的分组接口是通过后端配置不同的扫描包,将后端的接口,按配置的扫描包基础属性响应给前端

后端java的配置如下,指定分组名和各自要扫描的包

@Bean(value = "defaultApi")
public Docket defaultApi() {
    return new Docket(DocumentationType.SWAGGER_2)
        .apiInfo(apiInfo())
        .groupName("默认接口")
        .select()
        .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
        .paths(PathSelectors.any())
        .build();
}
@Bean(value = "groupApi")
public Docket groupRestApi() {
    return new Docket(DocumentationType.SWAGGER_2)
        .apiInfo(groupApiInfo())
        .groupName("分组接口")
        .select()
        .apis(RequestHandlerSelectors.basePackage("com.example.demo.group"))
        .paths(PathSelectors.any())
        .build();
}

在swagger-ui中也可以通过分组来查看api文档

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值