Swagger

依赖

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

配置类

package com.swaggerTest;
 
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配置类
 * 在与spring boot集成时,放在与Application.java同级的目录下。
 * 通过@Configuration注解,让Spring来加载该类配置。
 * 再通过@EnableSwagger2注解来启用Swagger2。
 */
@Configuration
@EnableSwagger2
public class Swagger2 {
    
    /**
     * 创建API应用
     * apiInfo() 增加API相关信息
     * 通过select()函数返回一个ApiSelectorBuilder实例,用来控制哪些接口暴露给Swagger来展现,
     * 本例采用指定扫描的包路径来定义指定要建立API的目录。
     * 
     * @return
     */
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.swaggerTest.controller"))
                .paths(PathSelectors.any())
                .build();
    }
    
    /**
     * 创建该API的基本信息(这些基本信息会展现在文档页面中)
     * 访问地址:http://项目实际地址/swagger-ui.html
     * @return
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring Boot中使用Swagger2构建RESTful APIs")
                .description("更多请关注http://www.baidu.com")
                .termsOfServiceUrl("http://www.baidu.com")
                .contact("sunf")
                .version("1.0")
                .build();
    }
}
 

添加文档内容

在完成了上述配置后,其实已经可以生产文档内容,但是这样的文档主要针对请求本身,描述的主要来源是函数的命名,对用户并不友好,我们通常需要自己增加一些说明来丰富文档内容。

Swagger使用的注解及其说明:

@api:用在类上,说明该类的作用。

valueurl的路径值
tags如果设置这个值、value的值会被覆盖
description对api资源的描述
basePath基本路径可以不配置
position如果配置多个Api 想改变显示的顺序位置
producesFor example, "application/json, application/xml"
consumesFor example, "application/json, application/xml
protocolsPossible values: http, https, ws, wss.
authorizations高级特性认证时配置
hidden配置为true 将在文档中隐藏

@ApiOperation:注解来给API增加方法说明。

valueurl的路径值
tags如果设置这个值、value的值会被覆盖
description对api资源的描述
response返回的对象
hidden配置为true 将在文档中隐藏
httpMethod"GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS" and "PATCH"
codehttp的状态码 默认 200
basePath基本路径可以不配置
position如果配置多个Api 想改变显示的顺序位置
producesFor example, "application/json, application/xml"
consumesFor example, "application/json, application/xml"
protocolsPossible values: http, https, ws, wss.
responseContainer这些对象是有效的 "List", "Set" or "Map".,其他无效
authorizations高级特性认证时配置
extensions扩展属性

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

@ApiImplicitParam:用在@ApiImplicitParams注解中,指定一个请求参数的各个方面

  • paramType:参数放在哪个地方

  • name:参数代表的含义

  • value:参数名称

  • dataType: 参数类型,有String/int,无用

  • required : 是否必要

  • defaultValue:参数的默认值

@ApiResponses:用于表示一组响应

@ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息

l code:数字,例如400

l message:信息,例如"请求参数没填好"

l response:抛出异常的类

@ApiModel:描述一个Model的信息(一般用在请求参数无法使用@ApiImplicitParam注解进行描述的时候)

@ApiModelProperty**:描述一个model的属性

例子

/**
 * @Auther: wyq
 * @Date: 2018/12/29 14:50
 */
@RestController
@Api(value = "电影Controller", tags = { "电影访问接口" })
@RequestMapping("/film")
public class FilmController {
​
    @Autowired
    private FilmService filmService;
​
    /**
     * 添加一个电影数据
     *
     * @param
     * @return
     */
    @ApiOperation(value = "添加一部电影")
    @PostMapping("/addFilm")
    @ApiResponses(value = { @ApiResponse(code = 1000, message = "成功"), @ApiResponse(code = 1001, message = "失败"),
            @ApiResponse(code = 1002, response = Film.class,message = "缺少参数") })
    public ResultModel addFilm(@ApiParam("电影名称") @RequestParam("filmName") String filmName,
                               @ApiParam(value = "分数", allowEmptyValue = true) @RequestParam("score") Short score,
                               @ApiParam("发布时间") @RequestParam(value = "publishTime",required = false) String publishTime,
                               @ApiParam("创建者id") @RequestParam("creatorId") Long creatorId) {
​
        if (Objects.isNull(filmName) || Objects.isNull(score) || Objects.isNull(publishTime) || StringUtils
                .isEmpty(creatorId)) {
            return new ResultModel(ResultModel.failed, "参数错误");
        }
        Film filmPOM = new Film();
        filmPOM.setFilmName(filmName);
        filmPOM.setScore(score);
        DateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date publishTimeDate = null;
        try {
            publishTimeDate = simpleDateFormat.parse(publishTime);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        filmPOM.setPublishTime(publishTimeDate);
        filmPOM.setCreatorId(creatorId);
        Boolean result = filmService.addFilm(filmPOM);
        if (result) {
            return new ResultModel(CommonConstants.SUCCESSMSG);
        }
        return new ResultModel(CommonConstants.FAILD_MSG);
    }
​
    /**
     * 根据电影名字获取电影
     *
     * @param fileName
     * @return
     */
    @GetMapping("/getFilms")
    @ApiOperation(value = "根据名字获取电影")
    @ApiResponses(value = { @ApiResponse(code = 1000, message = "成功"), @ApiResponse(code = 1001, message = "失败"),
            @ApiResponse(code = 1002, message = "缺少参数") })
    public ResultModel getFilmsByName(@ApiParam("电影名称") @RequestParam("fileName") String fileName) {
        if (StringUtils.isEmpty(fileName)) {
            return CommonConstants.getErrorResultModel();
        }
​
        List<Film> films = filmService.getFilmByName(fileName);
        if (!CollectionUtils.isEmpty(films)) {
            return new ResultModel(films);
        }
        return CommonConstants.getErrorResultModel();
​
    }
​
    /**
     * 根据电影名更新
     *
     * @return
     */
    @PostMapping("/updateScore")
    @ApiOperation(value = "根据电影名修改分数")
    @ApiResponses(value = { @ApiResponse(code = 1000, message = "成功"), @ApiResponse(code = 1001, message = "失败"),
            @ApiResponse(code = 1002, message = "缺少参数") })
    public ResultModel updateFilmScore(@ApiParam("电影名称") @RequestParam("fileName") String fileName,
                                       @ApiParam("分数") @RequestParam("score") Short score) {
        if (StringUtils.isEmpty(fileName) || Objects.isNull(score)) {
            return CommonConstants.getErrorResultModel();
        }
​
        filmService.updateScoreByName(fileName, score);
        return CommonConstants.getSuccessResultModel();
    }
​
    /**
     * 根据电影名删除电影
     *
     * @param request
     * @return
     */
    @PostMapping("/delFilm")
    @ApiOperation(value = "根据电影名删除电影")
    @ApiImplicitParams({ @ApiImplicitParam(name = "filmName",
            value = "电影名",
            dataType = "String",
            paramType = "query",
            required = true), @ApiImplicitParam(name = "id", value = "电影id", dataType = "int", paramType = "query") })
    public ResultModel deleteFilmByNameOrId(HttpServletRequest request) {
        //电影名
        String filmName = request.getParameter("filmName");
        //电影id
        Long filmId = Long.parseLong(request.getParameter("id"));
​
        filmService.deleteFilmOrId(filmName,filmId);
​
​
        return CommonConstants.getSuccessResultModel();
    }
​
    /**
     * 根据id获取电影
     *
     * @param id
     * @return
     */
    @PostMapping("/{id}")
    @ApiOperation("根据id获取电影")
    @ApiImplicitParam(name = "id", value = "电影id", dataType = "long", paramType = "path", required = true)
    public ResultModel getFilmById(@PathVariable Long id) {
​
        if (Objects.isNull(id)) {
            return CommonConstants.getLessParamResultModel();
        }
        Film film = filmService.getFilmById(id);
        if (Objects.nonNull(film)) {
            return new ResultModel(film);
        }
        return CommonConstants.getErrorResultModel();
    }
​
    /**
     * 修改整个电影
     *
     * @param film
     * @return
     */
    @PostMapping("/insertFilm")
    @ApiOperation("插入一部电影")
    public ResultModel insertFilm(@ApiParam("电影实体对象") @RequestBody Film film) {
        if (Objects.isNull(film)) {
            return CommonConstants.getLessParamResultModel();
        }
        Boolean isSuccess = filmService.insertFilm(film);
        if (isSuccess) {
            return CommonConstants.getSuccessResultModel();
        }
        return CommonConstants.getErrorResultModel();
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值