swagger在springboot上的快速上手

Swagger是一款RESTFUL接口的文档在线自动生成+功能测试功能软件.

首先,在pom文件引入如下依赖位置:

        
            io.springfox
            springfox-swagger2
            2.2.2
        
        
            io.springfox
            springfox-swagger-ui
            2.2.2
        

首先,创建Swagger配置类

package com.example.demo.swagger2;

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.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/*
    swagger2的配置类
    @Configuration使spring加载此类
    @EnableSwagger2启用swagger2
 */
@Configuration
@EnableSwagger2
public class Swagger2 {
    /**
     * 创建API应用
     * 通过select()函数返回ApiSelectorBuilder实例,用来控制哪些接口暴露给swagger来展现
     * 这里使用指定包路径来展示
     * @return
     */
    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo()).select()
                .apis(RequestHandlerSelectors.basePackage("com.example.demo.swagger2"))
                .paths(PathSelectors.any())
                .build();
    }
    /**
     * 该方法主要配置一些api的基本信息(会展示)
     * 访问地址:http://项目实际地址/swagger-ui.html
     * @return
     */
    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("springboot 使用swagger2构建 RestApis")
                .description("更多请关注https://mp.csdn.net/postedit/84584783")
                .termsOfServiceUrl("https://mp.csdn.net/postedit/84584783")
                .contact("han")
                .version("1.0")
                .build();
    }
}

接下来,我们来看看常用的注解

@Api:用在类上说明,此类的作用

@ApiOperation:用在方法上说明,此方法的作用

@ApiImplicitParams:用在方法上包含一组参数说明

@ApiImplicitParam:用来注解来给方法入参说明

     -- paramType:指定参数放在请求的那个地方

             --header:请求参数放置于Request Header,使用@RequestHeader获取

             -- query:请求参数放置于请求地址,使用@RequestParam获取

             -- path:请求参数放置于url地址栏,使用@PathVariable获取(restful接口)

             -- body:请求参数放置于请求体

             -- form:请求参数以表单形式放置

       -- name:参数名

       -- value:参数说明

       -- required:参数是否必传

       -- dataType:参数类型

       -- defaultValue:默认的参数值

以下是参数为基本类型的示例:

package com.example.demo.swagger2;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@Api(value = "SwaggerController|一个用来测试swagger的控制类",tags = {"测试swagger类"})
@RequestMapping("/swagger")
public class SwaggerController {
    @ResponseBody
    @RequestMapping(value = "/getName",method = RequestMethod.GET)
    @ApiOperation(value = "根据用户id获取用户名称",notes = "test:请勿传入汉字,且不能大于2")
    @ApiImplicitParam(paramType = "query",name = "userId",value = "用户id",required = true,dataType = "Integer")
    public String getName(@RequestParam Integer userId){
        if (userId == 1){
            return "杨雪";
        } else if (userId == 2) {
            return "杨胖";
        } else {
            return "杨猪";
        }
    }
    @ResponseBody
    @RequestMapping(value = "/updatePassword",method = RequestMethod.GET)
    @ApiOperation(value = "根据用户id,修改用户密码",notes = "Test:id不能大于2")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "userId",value = "用户id",required = true,dataType = "Integer"),
            @ApiImplicitParam(paramType = "query",name = "password",value = "旧密码",required = true,dataType = "String"),
            @ApiImplicitParam(paramType = "query",name = "newPassword",value = "新密码",required = true,dataType = "String")
    })
    public String updatePassword(@RequestParam(value = "userId") Integer userId,@RequestParam(value = "password") String password,@RequestParam(value = "newPassword") String newPassword){
        if (userId >= 2 || userId <= 0) {
            return "不认识的";
        }
        if (StringUtils.isEmpty(password) || StringUtils.isEmpty(newPassword)) {
            return "密码不能为空";
        }
        if (password.equals(newPassword)) {
            return "新旧密码不能相同";
        }
        return "密码修改成功";
    }
}

完成上述代码添加上,启动Spring Boot程序,访问:http://localhost:8080/swagger-ui.html

swagger在springboot上的快速上手_第1张图片

如上图,我们可以在生成的文档上直接对代码进行测试,此处类似使用postman,就不在赘述了.

最后,我们来看下如果接收的参数是对象如何接收:

@ApiModel:用在pojo类上,对类进行说明

@ApiModelProperty:用在pojo类的属性上,对属性进行注入

下面直接上示例:

package com.example.demo.swagger2;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

@Data
@ApiModel(value = "医生对象模型")
public class Doctor {

    @ApiModelProperty(value = "id",required = true)
    private Integer id;

    @ApiModelProperty(value = "name",required = true)
    private String name;
}
package com.example.demo.swagger2;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.HttpStatusCodeException;

@Controller
@RequestMapping("/doctorSwagger")
@Api(value = "医生信息接口模拟")
public class DoctorSwaggerController {

    @RequestMapping(value = "/addDoctor",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "添加医生信息",notes = "直接添加对象")
    public String addDoctor(@RequestBody Doctor doctor) throws Exception{
        if (doctor == null || doctor.getId() == null)
            throw new Exception("添加医生信息失败,实体为null");
        try {
            System.out.println("添加医生信息成功"+doctor.getName());
        } catch (Exception e) {
            throw new Exception("添加医生信息失败,原因未知");
        }
        return doctor.getId().toString();
    }
}

此处需注意的是swagger自带的工具采用的是json传参,测试时需要在参数上加上@ResponseBody,正常运行使用form或URL时,删除即可.

 

 

你可能感兴趣的:(java工具,swagger)