spring boot集成最新swagger2构建Restful API

1、pom文件下加入如下依赖

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

  版本信息,能够经过swagger官网查询,或经过maven仓库搜索html

2、在项目中加入配置类

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;

@Configuration
@EnableSwagger2
public class Swagger2Config {
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
        .apiInfo(apiInfo())
        .select()
     .apis(RequestHandlerSelectors.basePackage(
"com.example")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo(){ return new ApiInfoBuilder() .title("Spring Boot————Swagger2构建Restful APIs") .description("消息中心使用") .termsOfServiceUrl("https://swagger.io") .version("1.0") .build(); } }

3、在对应的controller中使用Restful Api的相关注解,以下:

//代替@responsebody和@Controller,返回json格式
@RestController
//方法的描述
@ApiOperation
//单个参数
@ApiImplicitParam(name = "",value = "",requires = true/false,dataType = "")
//多个参数
@ApiImplicitParams{
  @ApiImplicitParam(name = "",value = "",requires = true/false,dataType = ""),
  @ApiImplicitParam(name = "",value = "",requires = true/false,dataType = "")	
}
//配置url映射
@RequestMapping
//url中占位参数
@PathVariable

开启本地服务,访问http://localhost:8080/swagger-ui.html,便可看到相应界面!

附:RESTFUL API各请求方法以下,

  1.GET

  通常用于执行查询操做。get请求中URL有长度限制,而且url中的数据都明文暴露。java

  2.POST

  在作一些修改的操做的时候使用,突破了长度限制,且数据存放在body中。web

  3.HEAD

  HEAD请求只会返回首部的信息,不会返回相应体。一般用于测试数据是否存在,能够作心跳测试等。spring

  4.PUT

  与GET相反,用于改变某些内容。json

  5.DELETE

  删除某些资源时使用。api

  6.TRACE

  用于观察某一请求在到达服务前的变化,该请求会在到达服务前的最后一步返回原始信息,以此来观察到,数据在中间传输时是否有过修改。安全

  常常用于跨站攻击,有必定的安全隐患。服务器

  7.OPTIONS

  询问服务器支持的方法restful

  8.PATCH

  用于更新部分字段时使用,区别于PUT的所有提交,当更新的部分数据不存在时则新建,相似于neworupdate。架构

  更多详情可查看RESTFUL架构详解

相关文章
相关标签/搜索