SpringBoot 整合Swagger2

如果项目上使用了Swagger做RESTful的文档,那么也可以通过Swagger提供的代码生成器生成客户端代码,同时支持Feign客户端。

一、整合使用步骤:
  • 导入pom依赖
		<!--swagger2 -->
        <dependency>
            <groupId>com.spring4all</groupId>
            <artifactId>swagger-spring-boot-starter</artifactId>
            <version>1.9.1.RELEASE</version>
        </dependency>
  • 创建Swagger2的配置类
package com.huawei;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

@Configuration
public class Swagger2Config {
    public static final String SWAGGER_SCAN_BASIC_PACKAGE = "com.huawei.controller";
    public static final String VERSION ="1.0.0";

    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage(SWAGGER_SCAN_BASIC_PACKAGE))//api接口包扫描路径
                .paths(PathSelectors.any())//可以根据url路径设置哪些请求加入文档,忽略哪些请求
                .build();
    }

    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("RestApi在线文档")
                .description("在线文档")//设置文档的描述->1.Overview
                .version(VERSION)//设置文档的版本信息-> 1.1 Version information
                .contact(new Contact("snailjw", "https://github.com/SnailSjw", "songjwmail@163.com"))//设置文档的联系方式->1.2 Contact information
                .termsOfServiceUrl("暂无")//设置文档的License信息->1.3 License information
                .build();
    }
}
  • 在启动类上使用注解@EnableSwagger2开启Swagger2的功能
二、使用注解标记接口
  • @ApiOperation
  • @ApiResponses 增加返回结果的描述
    @GetMapping("/hello")
    @ApiOperation(value="测试整合", notes="第一个测试接口Hello",produces = "application/json")
	@ApiResponses(value = {@ApiResponse(code = 200,message = "success")})
    public String Hello(){
        return helloService.hello();
    }
  • @ApiImplicitParam 描述接口参数
    @ApiOperation(value="获取用户详细信息", notes="根据url的id来获取用户详细信息",produces = "application/json")
    @ApiResponses(value = {@ApiResponse(code = 405,message = "Invalid input",response = Integer.class)}) (1)
    @ApiImplicitParam(name = "id",value = "用户ID",dataType = "int",paramType = "path")  (2)
    @RequestMapping(value="/users/{id}", method= RequestMethod.GET)
    public User getUser(@PathVariable Integer id) {
        return users.get(id);
    }
  • @ApiImplicitParams 描述多个接口参数
    @ApiOperation(value="更新用户名称", notes="更新指定用户的名称")
    @RequestMapping(value="/users/{id}", method= RequestMethod.POST)
    @ApiImplicitParams({ 
            @ApiImplicitParam(name = "id",value = "用户ID",paramType = "path",dataType = "int"),  
            @ApiImplicitParam(name = "userName",value = "用户名称",paramType = "form",dataType = "string") })
    public void updateUserName(@PathVariable Integer id,@RequestParam String userName){
        User u = users.get(id);
        u.setName(userName);
    }

使用@ApiImplicitParam时,需要指定paramType,这样也便于swagger ui 生成参数的输入格式。

paramType 有五个可选值 : path, query, body, header, form

  • @ApiParam 需要给参数添加描述时可以使用这个注解

    	@ApiOperation(value="创建用户-传递简单对象", notes="传递简单对象",produces = "application/json")
        @RequestMapping(value="/users-1", method= RequestMethod.POST)
        public Map postUser(@RequestParam  String userName,@ApiParam("地址") @RequestParam(required = false) String address) {
            User user = new User();
            user.setId(Math.round(10));
            user.setName(userName);
            user.setAddress(address);
            users.put(user.getId(), user);
            return ImmutableMap.of("user",user);
        }
    
    • @ApiParam与@ApiImplicitParam的区别
      • 对Servlets或者非 JAX-RS的环境,只能使用 ApiImplicitParam。
      • 在使用上,ApiImplicitParam比ApiParam具有更少的代码侵入性,只要写在方法上就可以了,但是需要提供具体的属性才能配合swagger ui解析使用。
      • ApiParam只需要较少的属性,与swagger ui配合更好。
  • @ModelAttribute 传递对象推荐使用(ModelAttribute 是Spring mvc的注解,这里Swagger可以解析这个注解,获得User的属性描述)

        @ApiOperation(value="创建用户-传递复杂对象", notes="传递复杂对象DTO, url参数拼接",produces = "application/json")
        @RequestMapping(value="/users-2", method= RequestMethod.POST)
        public Map postUser2(@ModelAttribute User user) {  (1)
            users.put(user.getId(),user);
            return ImmutableMap.of("user",user);
        }
    
    • @ApiModel在实体类上标记
    @ApiModel(value = "User", description = "用户对象")
    public class User {
    
        @ApiModelProperty(value = "ID")
        private Integer id;
        @ApiModelProperty(value = "姓名")
        private String name;
        @ApiModelProperty(value = "地址")
        private String address;
        @ApiModelProperty(value = "年龄",access = "hidden")
        private int age;
        @ApiModelProperty(value = "性别")
        private int sex;
        .......
    }
    
  • @RequestBody传递复杂对象时使用(使用json格式传递对象使用RequestBody注解)

    @ApiOperation(value="创建用户-传递复杂对象", notes="传递复杂对象DTO,json格式传递数据",produces = "application/json")
    @RequestMapping(value="/users-3", method= RequestMethod.POST)
    public User postUser3(@RequestBody User user) {
        users.put(user.getId(),user);
        return user;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值