《深入理解Spring Cloud与微服务构建》学习笔记(七)~SpringBoot 整合 Swagger2,搭建在线api文档

一、在项目 pom.xml 引入 swagger 依赖 springfox-swagger2 和 springfox-swagger-ui 如:

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

二、配置Swagger2
     新建一个配置类,添加@Configuration注解 ,表明是一个配置类,添加@EnableSwagger2注解,开启Swagger2功能。还需要注入一个Docket的Bean,该Bean包含了apiInfo,基本api文档的描述信息,以及包扫描的基本包名信息如:


@Configuration
@EnableSwagger2
public class Swagger2 {

    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.snail.test.spring_boot_demo1024"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("构建Swagger2在线文档")
                .description("使用Spring Boot 构建")
                .termsOfServiceUrl("http://localhost:8080")
                .version("1.0")
                .build();
    }
}

三、写生成文档注解
Swagger2通过注解生成api文档,常用的一些注解如下:
@Api: 修饰整个类,用于描述Controller
@ApiOperation :描述类的方法,或者说一个接口
@ApiParam:单个参数描述
@ApiModel:”用对象来接收参数。
@ApiProperty:用对象接收参数时,描述对象的一个字段
@ApiResponse: HTTP 响应的一个描述。
@ApiResponses: HTTP 响应的整体描述。
@Apilgnore: 使用该注解,表示 Swagger2 忽略这个 API
@ApiError: 发生错误返回的信息。
@ApiParamlmplicit: 一个请求参数
@ApiParamsimplicit: 多个请求参数。
四、Web层
 新建一个Controller,新建一个方法,构建一个以资源为中心的 RESTful 风格的 API 接口。
方法需要通过 @ApiOperation 注解描述当前api的具体说明,value为接口名字,notes为该接口详细描述说明。
如果不需要生成则加入 @Apilgnore 注解即可。代码如下:

@RequestMapping("/user")
@RestController
public class UserController {


    @ApiOperation(value = "用户列表" , notes = "用户列表notes")
    @RequestMapping(value="",method = RequestMethod.GET)
    public List<String> getUser(){
        List<String> list = new ArrayList();
        return list ;
    }
}

启动项目,访问:http://localhost:8080/swagger-ui.html   可以看到一个简单的在线文档构建完成:

demo代码:https://download.csdn.net/download/ssdate/10741152

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值