spring boot整合Swagger来操作api

Posted 蜗牛的坚持

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring boot整合Swagger来操作api相关的知识,希望对你有一定的参考价值。

 

1.pom.xml

<!--Swagger2 - RESTful API文档-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.6.1</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.6.1</version>
        </dependency>

2.Application.java

package com.guilf;



import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;


/**
 * 注:启动类不要放在main/java 根目录下,启动会报错
 */
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
}

3.SwaggerConfig.java

package com.guilf;

import com.google.common.base.Predicate;
import org.springframework.boot.autoconfigure.web.BasicErrorController;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.RequestHandler;
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 // 启用 Swagger
public class SwaggerConfig {

    @Bean
    public Docket createRestApi() {

        /**
         * Swagger会默认把所有Controller中的RequestMapping方法都生成API出来,实际上我们一般只需要标准接口的(像返回页面的那种Controller方法我们并不需要),
         * 所有你可以按下面的方法来设定要生成API的方法的要求。
         * 如下我针对RestController注解的类和ResponseBody注解的方法才生成Swaager的API,并且排除了特定的类
         */
        Predicate<RequestHandler> predicate = new Predicate<RequestHandler>() {
            public boolean apply(RequestHandler input) {
                Class<?> declaringClass = input.declaringClass();
                if (declaringClass == BasicErrorController.class)// 排除
                    return false;
                if(declaringClass.isAnnotationPresent(RestController.class)) // 被注解的类
                    return true;
                if(input.isAnnotatedWith(ResponseBody.class)) // 被注解的方法
                    return true;
                return false;
            }
        };
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .useDefaultResponseMessages(false)
                .select()
                .apis(predicate)
                 // 这里设置api 生成的范围,有两种方式:
                 // 1.上面通过自定义过滤规则
                 // 2,通过定义需要生成API的包路径
                 //.apis(RequestHandlerSelectors.basePackage(SWAGGER_SCAN_BASE_PACKAGE))
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("用户信息接口的服务")//大标题
                .version("1.0")//版本
                .build();
    }
}

4.User.java

package com.guilf.domain;


public class User {

    private String id;
    private String name;
    private Integer age;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

 5.UserAPIController.java

package com.guilf.mvc;


import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import org.springframework.web.bind.annotation.*;

import com.guilf.domain.User;

import java.util.*;


/**
 * @ClassName: UserAPIController
 * @Description: (使用 swagger 展示API  )
 * 
 * @version v1.1
 */
@RestController
@RequestMapping("/users")
public class UserAPIController {

    static Map<String, User> users = Collections.synchronizedMap(new HashMap<String, User>());

    @ApiOperation(value = "获取用户列表",notes ="")
    @RequestMapping(value = "/",method = RequestMethod.GET)
    public List<User> getUserList(){
        // 处理"/users/"的GET请求,用来获取用户列表
        // 还可以通过@RequestParam从页面中传递参数来进行查询条件或者翻页信息的传递
        List<User> u = new ArrayList<>(users.values());
        return u;
    }

    @ApiOperation(value="创建用户", notes="根据User对象创建用户")
    @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
    @RequestMapping(value="/", method=RequestMethod.POST)
    public String postUser(@ModelAttribute User user) {
        // 处理"/users/"的POST请求,用来创建User
        // 除了@ModelAttribute绑定参数之外,还可以通过@RequestParam从页面中传递参数
        users.put(user.getId(), user);
        return "success";
    }

    @ApiOperation(value="获取用户信息", notes="根据用户ID获取对应用户信息")
    @ApiImplicitParams(@ApiImplicitParam(name ="id" ,value = "用户ID",required = true,dataType ="String"))
    @RequestMapping(value="/{id}", method=RequestMethod.GET)
    public User getUser(@PathVariable String id) {
        // 处理"/users/{id}"的GET请求,用来获取url中id值的User信息
        // url中的id可通过@PathVariable绑定到函数的参数中
        return users.get(id);
    }


    @ApiOperation(value ="修改用户信息",notes ="根据用户ID修改对应用户信息")
    @ApiImplicitParams({ @ApiImplicitParam(name ="id" ,value ="用户ID",required = true,dataType = "String"),
                         @ApiImplicitParam(name ="user",value ="用户实体对象",required = true,dataType = "User")})
    @RequestMapping(value="/{id}", method=RequestMethod.PUT)
    public String putUser(@PathVariable String id, @ModelAttribute User user) {
        // 处理"/users/{id}"的PUT请求,用来更新User信息
        User u = users.get(id);
        u.setName(user.getName());
        u.setAge(user.getAge());
        users.put(id, u);
        return "success";
    }

    @ApiOperation(value ="获取用户信息",notes = "根据用户ID删除对应用户信息")
    @ApiImplicitParam(name = "id",value = "用户ID",required = true,dataType = "String")
    @RequestMapping(value="/{id}", method=RequestMethod.DELETE)
    public String deleteUser(@PathVariable String id) {
        // 处理"/users/{id}"的DELETE请求,用来删除User
        users.remove(id);
        return "success";
    }
}

  6.启动 ,y页面显示

http://localhost:8088/swagger-ui.html

7.新增,插入数据点Try it out

8.点查看

 

以上是关于spring boot整合Swagger来操作api的主要内容,如果未能解决你的问题,请参考以下文章

Spring Boot之Swagger2集成

Swagger Learing - Spring Boot 整合swagger

Spring boot整合Swagger

Spring Boot整合Swagger2

spring boot和swagger 整合

Spring Boot 整合Swagger 第二部 (动态配置启动Swagger,API分组管理)