Fork me on GitHub

springboot swagger2案例

 

非原创,哪位老哥的也不记得了。。。

没啥好说的,就是api接口自动生成文档

源码:https://github.com/youxiu326/sb_swagger2.git

 

  • 引入依赖
		<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>

 

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.16.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.huarui</groupId>
    <artifactId>sb_swagger2</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>sb_swagger2</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <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>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
pom.xml

 

 

 

 

  • swagger2配置类
package com.youxiu326.config;

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.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * Created by lihui on 2019/1/22.
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {

    /**
     * swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包等等
     * @return
     */
    @Bean
    public Docket docket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.youxiu326.controller"))
                .paths(PathSelectors.any()).build();

    }


/*  以注解方式查询

    @Documented
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.METHOD,ElementType.TYPE})
    public @interface EnableApi {

    }


    @Bean
    public Docket createRestApi() {
        Predicate<RequestHandler> predicate = new Predicate<RequestHandler>() {
            @Override
            public boolean apply(RequestHandler input) {
                Class<?> declaringClass = input.declaringClass();
                if(declaringClass.isAnnotationPresent(EnableApi.class)) // 被注解的类
                    return true;
                if(input.isAnnotatedWith(EnableApi.class)) // 被注解的方法
                    return true;
                return false;
            }
        };
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .useDefaultResponseMessages(false)
                .select()
                .apis(predicate)
                .build();
    }*/

    //构建api文档的详细信息函数
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                //页面标题
                .title("springBoot测试使用Swagger2构建RESTful API")
                //创建人
                .contact(new Contact("youxiu326", "http://youxiu326.com", ""))
                //版本号
                .version("1.0")
                //描述
                .description("API 描述")
                .build();
    }

}

 

  • 注解解释

 参数详解可参考:https://blog.csdn.net/jiangyu1013/article/details/83107255

主要参数:
@Api:修饰整个类,描述Controller的作用
  例如:@Api(value="书籍controller",tags={"书籍操作接口"})


@ApiOperation:描述一个类的一个方法,或者说一个接口
  例如
  @ApiOperation(value="form格式提交创建图书", notes="form格式提交创建图书(哈哈哈)")

    @ApiImplicitParams:用在请求的方法上,表示一组参数说明
    @ApiImplicitParam:用在@ApiImplicitParams注解中,指定一个请求参数的各个方面
        name:参数名
        value:参数的汉字说明、解释
        required:参数是否必须传
        paramType:参数放在哪个地方
            · header --> 请求参数的获取:@RequestHeader
            · query --> 请求参数的获取:@RequestParam
            · path(用于restful接口)--> 请求参数的获取:@PathVariable
            · body(不常用)
            · form(不常用)    
        dataType:参数类型,默认String,其它值dataType="Integer"       
        defaultValue:参数的默认值
  例如:
  @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "名称", required = true, dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "price", value = "价格", required = true, dataType = "float",paramType = "query")
    })


paramType 有五个可选值 : path, query, body, header, form
例如 我是从路径中去读的值  http://localhost:8088/bookcurd/1
  @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Long",paramType = "path")

Content-type常见类型:
  1.application/x-www-form-urlencoded
  2.application/json
  3.multipart/form-data
  4.text/xml
  consumes = "application/x-www-form-urlencoded;charset=utf-8"     指定处理请求的提交内容类型(Content-Type),例如application/json, text/html
  produces = "application/json;charset=utf-8"     返回json格式数据



@ApiParam:单个参数描述
@ApiModel:用对象来接收参数
@ApiProperty:用对象接收参数时,描述对象的一个字段
@ApiResponse:HTTP响应其中1个描述
@ApiResponses:HTTP响应整体描述
@ApiIgnore:使用该注解忽略这个API
@ApiError :发生错误返回的信息
@ApiParamImplicitL:一个请求参数
@ApiParamsImplicit 多个请求参数

 

 

 

 

package com.youxiu326.controller;

import com.youxiu326.entity.Book;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import java.util.*;

@RestController
@RequestMapping(value = "/bookcurd")
@Api("图书列表相关api")
public class BookController {

    /**
     *
     @Api:修饰整个类,描述Controller的作用
     @ApiOperation:描述一个类的一个方法,或者说一个接口
     @ApiParam:单个参数描述
     @ApiModel:用对象来接收参数
     @ApiProperty:用对象接收参数时,描述对象的一个字段
     @ApiResponse:HTTP响应其中1个描述
     @ApiResponses:HTTP响应整体描述
     @ApiIgnore:使用该注解忽略这个API
     @ApiError :发生错误返回的信息
     @ApiParamImplicitL:一个请求参数
     @ApiParamsImplicit 多个请求参数
     */

    /**Content-type常见类型:
     * 1.application/x-www-form-urlencoded
     * 2.application/json
     * 3.multipart/form-data
     * 4.text/xml
     * consumes = "application/x-www-form-urlencoded;charset=utf-8"     指定处理请求的提交内容类型(Content-Type),例如application/json, text/html
     * produces = "application/json;charset=utf-8"     返回json格式数据
     */


    Map<Long, Book> books = Collections.synchronizedMap(new HashMap<Long, Book>());

    @ApiOperation(value="获取图书列表", notes="获取图书列表")
    @RequestMapping(value={""}, method= RequestMethod.GET)
    public List<Book> getBook() {
        List<Book> book = new ArrayList<>(books.values());
        return book;
    }

    @ApiOperation(value="form格式提交创建图书", notes="form格式提交创建图书(哈哈哈)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "名称", required = true, dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "price", value = "价格", required = true, dataType = "float",paramType = "query")
    })
    @RequestMapping(value = "/saveBook",method = RequestMethod.POST,consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String saveBook(Book book){
        Book book1 = books.get(book.getId());
        if(book1 == null){
            book1 = new Book();
            book1.setId(new Random().nextLong());
        }
        book1.setName(book.getName());
        book1.setPrice(book.getPrice());
        books.put(book1.getId(), book1);
        // 这里返回json字符串
        return "{\"msg\":\"SUCCESS!\",\"state\":1}";
    }


    @ApiOperation(value="json格式提交创建图书", notes="json格式提交创建图书")
    @ApiImplicitParam(name = "book", value = "图书详细实体", required = true, dataType = "Book")
    @RequestMapping(value="", method=RequestMethod.POST)
    public String postBook(@RequestBody Book book) {
        books.put(book.getId(), book);
        return "SUCCESS";
    }
    @ApiOperation(value="获图书细信息", notes="根据url的id来获取详细信息")
    @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Long",paramType = "path")
    @RequestMapping(value="/{id}", method=RequestMethod.GET)
    public Book getBook(@PathVariable Long id) {
        return books.get(id);
    }

    @ApiOperation(value="更新信息", notes="根据url的id来指定更新图书信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "图书ID", required = true, dataType = "Long",paramType = "path"),
            @ApiImplicitParam(name = "book", value = "图书实体book", required = true, dataType = "Book")
    })
    @RequestMapping(value="/{id}", method= RequestMethod.PUT,produces = "application/json")
    public String putUser(@PathVariable Long id, @RequestBody Book book) {
        Book book1 = books.get(id);
        book1.setName(book.getName());
        book1.setPrice(book.getPrice());
        books.put(id, book1);
        return "SUCCESS";
    }

    @ApiOperation(value="删除图书", notes="根据url的id来指定删除图书")
    @ApiImplicitParam(name = "id", value = "图书ID", required = true, dataType = "Long",paramType = "path")
    @RequestMapping(value="/{id}", method=RequestMethod.DELETE)
    public String deleteUser(@PathVariable Long id) {
        books.remove(id);
        return "SUCCESS";
    }

    @ApiIgnore//使用该注解忽略这个API
    @RequestMapping(value = "/hi", method = RequestMethod.GET)
    public String jsonTest() {
        return " hi you!";
    }
}

 

  •  演示

 

 

 

posted @ 2019-11-09 20:49  youxiu326  阅读(508)  评论(1编辑  收藏  举报