spring boot集成最新swagger2构建Restful API


一、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仓库搜索

二、在项目中加入配置类

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(); } }

三、在对应的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中的数据都明文暴露。

  2.POST

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

  3.HEAD

  HEAD请求只会返回首部的信息,不会返回相应体。通常用于测试数据是否存在,可以做心跳测试等。

  4.PUT

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

  5.DELETE

  删除某些资源时使用。

  6.TRACE

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

  经常用于跨站攻击,有一定的安全隐患。

  7.OPTIONS

  询问服务器支持的方法

  8.PATCH

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

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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM