Restful+swagger2 Restful接口文档

一、Restful

 

1.什么是Restful?

  REST指的是一组架构约束条件和原则。REST并没有一个明确的标准,而更像是一种设计的风格。 如果一个架构符合REST的约束条件和原则,我们就称它为RESTful架构。

 

2.Restful的特点(摘自:百度百科)

  • 每一个URI代表1种资源;
  • 客户端使用GET、POST、PUT、DELETE4个表示操作方式的动词对服务端资源进行操作:GET用来获取资源,POST用来新建资源(也可以用于更新资源),PUT用来更新资源,DELETE用来删除资源;
  • 通过操作资源的表现形式来操作资源;
  • 资源的表现形式是XML或者HTML;
  • 客户端与服务端之间的交互在请求之间是无状态的,从客户端到服务端的每个请求都必须包含理解请求所必需的信息。

 

3.Restful的风格

    @RequestMapping(value = "selectOne/{id}",method = RequestMethod.GET)
    @ResponseBody
    public String selectOne(@PathVariable Integer id) {
        return JSON.toJSONString(this.infoService.queryById(id));
    }

Ps:

  1.这里需要注意的是@RequestMapping注解参数以{}传递,还要明确请求的方法,使用@PathVariable注解绑定参数(多个参数需要绑定参数名)。

  2.支持Restful风格的注解@PutMapping、@GetMapping、@DeleteMapping、@PostMapping

 

二、swagger的使用

 

1.添加swagger依赖

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

 

2.配置swagger

@Configuration
@EnableSwagger2
public class Swagger2 {

    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("Spring Boot 使用Swagger2构建API文档")
                .description("Restful风格的API")
                .version("1.0")
                .build();
    }

}

 

3.给需要产生接口文档的接口添加说明信息

@ApiOperation(value = "查询数据",notes = "根据主键查询单条数据")
@ApiImplicitParam(name = "id",value = "id",required = true,paramType = "path",dataType = "Long")
@RequestMapping(value = "selectOne/{id}",method = RequestMethod.GET)
@ResponseBody
public String selectOne(@PathVariable Integer id) {
return JSON.toJSONString(this.infoService.queryById(id));
}

 

4.重启项目,在地址栏中输入:http://localhost:8080/swagger-ui.html

 

5.swagger的补充

  在使用swagger的时候可能会出现404错误,下面提供一种解决方案(需要视具体情况而定,有可能解决你的问题)

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    public void addResourceHandlers(ResourceHandlerRegistry registry){
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
    }
}

 

Ps:在SpringBoot2x和Spring5x后的,有两种解决方案

  1.实现WebMvcConfigurer 接口

  2.继承WebMvcConfigurationSupport

posted @ 2020-02-19 19:15  lightbc  阅读(881)  评论(0编辑  收藏  举报