Spring Cloud 2.x系列之springcloud整合Swagger2构建Restful服务的APIs

 

Spring Cloud将服务注册到了Eureka上,可以从Eureka的UI界面中,看到有哪些服务已经注册到了EurekaServer上;但是如果想查看当前服务提供了哪些RESTful接口方法的话,就无法从Eureka Server获取了,而传统的方法是梳理一个接口文档来供开发人员之间来进行交流。这种情况下经常会造成文档和代码的不一致性,比如说代码改了,但是接口文档还没来得及修改等问题,而Swagger2则给我们提供了一套完美的解决方案,下面来看看Swagger2是如何来解决这个问题的。

 

1、        新建项目sc-swagger2,对应的pom.xml文件

 

<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.0http://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>


   <groupId>spring-cloud</groupId>

   <artifactId>sc-swagger2</artifactId>

   <version>0.0.1-SNAPSHOT</version>

   <packaging>jar</packaging>

   <name>sc-swagger2</name>

   <url>http://maven.apache.org</url>

   <parent>

      <groupId>org.springframework.boot</groupId>

      <artifactId>spring-boot-starter-parent</artifactId>

      <version>2.0.4.RELEASE</version>

   </parent>

   <dependencyManagement>

      <dependencies>

        <dependency>

           <groupId>org.springframework.cloud</groupId>

           <artifactId>spring-cloud-dependencies</artifactId>

           <version>Finchley.RELEASE</version>

           <type>pom</type>

           <scope>import</scope>

        </dependency>


      </dependencies>

   </dependencyManagement>


   <properties>

      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

      <maven.compiler.source>1.8</maven.compiler.source>

      <maven.compiler.target>1.8</maven.compiler.target>

   </properties>


   <dependencies>



      <dependency>

        <groupId>io.springfox</groupId>

        <artifactId>springfox-swagger2</artifactId>

        <version>2.9.2</version>

      </dependency>


      <dependency>

        <groupId>io.springfox</groupId>

        <artifactId>springfox-swagger-ui</artifactId>

        <version>2.9.2</version>

      </dependency>

      <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-web</artifactId>

      </dependency>

   </dependencies>

</project>

 

2、        新建springboot启动类

 

package sc.swagger2;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;


@SpringBootApplication

public class Swagger2Application {


public static void main(String[] args) {

       SpringApplication.run(Swagger2Application.class,args);

}


}

 

3、        新建Swagger2配置类

 

package sc.swagger2.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;



@Configuration

@EnableSwagger2

public class Swagger2Config {



@Bean
public DocketcreateRestApi() {

        return newDocket(DocumentationType.SWAGGER_2)

               .apiInfo(apiInfo())

                .select()

               .apis(RequestHandlerSelectors.basePackage("sc.swagger2"))

               .paths(PathSelectors.any())

                .build();

    }



    private ApiInfo apiInfo(){

        return newApiInfoBuilder()

               .title("Spring Boot中使用Swagger2构建RESTful APIs")

               .description("更多Spring Boot相关文章请关注: JAVA乐园  公众号")

               .termsOfServiceUrl("https://edu.csdn.net/lecturer/995")

                .contact(newContact("huangjinjin", //

                       "https://edu.csdn.net/lecturer/995",//

                       "happyhuangjinjin@sina.com"))

               .version("1.0")

                .build();

    }

}

 

4、        新建一个模拟的Controller

 

package sc.swagger2.controller;



import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;



import org.springframework.stereotype.Controller;

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

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

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

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

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

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

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

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



import io.swagger.annotations.Api;

import io.swagger.annotations.ApiImplicitParam;

import io.swagger.annotations.ApiImplicitParams;

import io.swagger.annotations.ApiOperation;

import io.swagger.annotations.ApiResponse;

import io.swagger.annotations.ApiResponses;

import sc.swagger2.model.User;



@Api(value="用户管理")

@Controller

publicclass UserController{



   @ApiResponses({ @ApiResponse(code =000000, message = "操作成功"),

      @ApiResponse(code =000001, message = "服务器内部异常") })

   @GetMapping(value = "/feign/user/getUser/{id}")

   @ResponseBody

   @ApiOperation(value = "获取根据Id用户信息",response = User.class)

   @ApiImplicitParam(name = "id", value= "用户ID", required = true, dataType = "Long",example="100")

   publicMap<String, Object> getUser(@PathVariable Long id) {

      Map<String,Object> result = new HashMap<String, Object>();

      result.put("code", "000000");

      result.put("msg", "success");

      User u = new User();

      u.setId(1L);

      u.setAge(23);

      u.setUserName("huangjinjin");

      u.setPosition("cto");

      result.put("body", u);

      returnresult;

   }



   @ApiResponses({ @ApiResponse(code =000000, message = "操作成功"),

      @ApiResponse(code =000001, message = "服务器内部异常") })

   @RequestMapping(value = "/feign/user/listUser", method = RequestMethod.GET)

   @ResponseBody

   @ApiOperation(value = "获取用户列表")

   public Map<String, Object> listUser() {

      Map<String,Object> result = new HashMap<String, Object>();

      result.put("code", "000000");

      result.put("msg", "success");

      User u = new User();

      u.setId(1L);

      u.setAge(23);

      u.setUserName("huangjinjin");

      u.setPosition("cto");

      List<User> list = newArrayList<User>();

      list.add(u);

      result.put("body", list);

      returnresult;

   }



   @ApiResponses({ @ApiResponse(code =000000, message = "操作成功"),

      @ApiResponse(code =000001, message = "服务器内部异常") })

   @PostMapping(value = "/feign/user/addUser")

   @ResponseBody

   @ApiOperation(value = "添加用户", notes = "根据User对象创建用户")

   @ApiImplicitParams({ @ApiImplicitParam(name = "userName", value = "用户名", required = true, dataType = "String"),

      @ApiImplicitParam(name = "age", value = "年龄", required = true, dataType = "String"),

      @ApiImplicitParam(name = "position", value = "职位", required = true, dataType = "String"),

      @ApiImplicitParam(name = "id", value = "用户ID", required = false, dataType = "Long",example="100")})

   public Map<String, Object> addUser(User user) {

      Map<String,Object> result = new HashMap<String, Object>();

      result.put("code", "000000");

      result.put("msg", "success");

      result.put("body", 1);

      returnresult;

   }


   @ApiResponses({ @ApiResponse(code =000000, message = "操作成功"),

      @ApiResponse(code =000001, message = "服务器内部异常") })

   @ApiOperation(value = "更新用户")

   @PutMapping(value = "/feign/user/updateUser")

   @ResponseBody

   @ApiImplicitParams({ @ApiImplicitParam(name = "userName", value = "用户名", required = true, dataType = "String"),

      @ApiImplicitParam(name = "age", value = "年龄", required = true, dataType = "String"),

      @ApiImplicitParam(name = "position", value = "职位", required = true, dataType = "String"),

      @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long", example="100")})

   public Map<String, Object> updateUser(User user) {

      Map<String,Object> result = new HashMap<String, Object>();

      result.put("code", "000000");

      result.put("msg", "success");

      result.put("body", 1);

      returnresult;

   }



   @ApiResponses({ @ApiResponse(code =000000, message = "操作成功"),

  @ApiResponse(code =000001, message = "服务器内部异常") })

   @DeleteMapping(value = "/feign/user/deleteUser/{id}")

   @ResponseBody

   @ApiOperation(value = "删除用户")

   @ApiImplicitParam(name = "id", value= "用户ID", required = true, dataType = "Long",example="100")

   public Map<String, Object> deleteUser(@PathVariable Long id) {

      Map<String, Object>result = new HashMap<String, Object>();

      result.put("code", "000000");

      result.put("msg", "success");

      result.put("body", 1);

      returnresult;

   }


}

 

5、        新建User模型类

 

package sc.swagger2.model;



import java.io.Serializable;



import io.swagger.annotations.ApiModel;

import io.swagger.annotations.ApiModelProperty;



@ApiModel

public class User implements Serializable {


private static final longserialVersionUID = 4639927446947303736L;



@ApiModelProperty(name="id",dataType="Long", value="主键ID")
private Long id;


@ApiModelProperty(name="userName",dataType="String", value="姓名", required=true)
private String userName;

@ApiModelProperty(name="age",dataType="String", value="年龄", required=true)
private Integer age;


@ApiModelProperty(name="position",dataType="String", value="职位")

private String position;



public String getUserName() {

       return userName;

}



public void setUserName(StringuserName) {

       this.userName =userName;

}

public Integer getAge() {

       return age;

}


public void setAge(Integerage) {

       this.age = age;

}



public String getPosition() {

       return position;

}


public void setPosition(Stringposition) {

       this.position =position;

}

public Long getId() {

       return id;

}

public void setId(Long id) {

       this.id = id;

}

}

 

6、        启动sc-swagger2项目,并验证是否启动成功

方式一:查看日志

 

                         

方式二:访问地址

http://127.0.0.1:9092/swagger-ui.html

或者访问http://localhost:9092/v2/api-docs

 

7、        在界面http://127.0.0.1:9092/swagger-ui.html点击【user-controller】可以看到所有的接口,同时也可以在界面上进行接口调用调试

源码:

https://gitee.com/hjj520/spring-cloud-2.x

swagger2注解详细说明

@Api:用在请求的类上,表示对类的说明
    tags="说明该类的作用,可以在UI界面上看到的注解"
    value="该参数没什么意义,在UI界面上也看到,所以不需要配置"

    
@ApiOperation:用在请求的方法上,说明方法的用途、作用
    value="说明方法的用途、作用"
    notes="方法的备注说明"

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

        
@ApiResponses:用在请求的方法上,表示一组响应
    @ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息
        code:数字,例如400
        message:信息,例如"请求参数没填好"
        response:抛出异常的类

        
@ApiModel:用于响应类上,表示一个返回响应数据的信息
            (这种一般用在post创建的时候,使用@RequestBody这样的场景,
            请求参数无法使用@ApiImplicitParam注解进行描述的时候)
    @ApiModelProperty:用在属性上,描述响应类的属性

(1)@Api:用在请求的类上,说明该类的作用

@Api:用在请求的类上,说明该类的作用
    tags="说明该类的作用"
    value="该参数没什么意义,所以不需要配置"

(2)@ApiOperation:用在请求的方法上,说明方法的作用

@ApiOperation:"用在请求的方法上,说明方法的作用"
    value="说明方法的作用"
    notes="方法的备注说明"

示例: 

@ApiOperation(value="用户注册",notes="手机号、密码都是必输项,年龄随边填,但必须是数字")

(3)@ApiImplicitParams:用在请求的方法上,包含一组参数说明 

@ApiImplicitParams:用在请求的方法上,包含一组参数说明
    @ApiImplicitParam:用在 @ApiImplicitParams 注解中,指定一个请求参数的配置信息       
        name:参数名
        value:参数的汉字说明、解释
        required:参数是否必须传
        paramType:参数放在哪个地方
            · header --> 请求参数的获取:@RequestHeader
            · query --> 请求参数的获取:@RequestParam
            · path(用于restful接口)--> 请求参数的获取:@PathVariable
            · body(不常用)
            · form(不常用)    
        dataType:参数类型,默认String,其它值dataType="Integer"       
        defaultValue:参数的默认值

示例:

@ApiImplicitParams({
    @ApiImplicitParam(name="mobile",value="手机号",required=true,paramType="form"),
    @ApiImplicitParam(name="password",value="密码",required=true,paramType="form"),
    @ApiImplicitParam(name="age",value="年龄",required=true,paramType="form",dataType="Integer")
})

(4)@ApiResponses:用于请求的方法上,表示一组响应 

@ApiResponses:用于请求的方法上,表示一组响应
    @ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息
        code:数字,例如400
        message:信息,例如"请求参数没填好"
        response:抛出异常的类

示例:

@ApiOperation(value = "select1请求",notes = "多个参数,多种的查询参数类型")
@ApiResponses({
    @ApiResponse(code=400,message="请求参数没填好"),
    @ApiResponse(code=404,message="请求路径没有或页面跳转路径不对")
})

(5)@ApiModel:用于响应类上,表示一个返回响应数据的信息  

@ApiModel:用于响应类上,表示一个返回响应数据的信息
            (这种一般用在post创建的时候,使用@RequestBody这样的场景,
            请求参数无法使用@ApiImplicitParam注解进行描述的时候)
    @ApiModelProperty:用在属性上,描述响应类的属性

示例:

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

import java.io.Serializable;

@ApiModel(description= "返回响应数据")
public class RestMessage implements Serializable{

    @ApiModelProperty(value = "是否成功")
    private boolean success=true;
    @ApiModelProperty(value = "返回对象")
    private Object data;
    @ApiModelProperty(value = "错误编号")
    private Integer errCode;
    @ApiModelProperty(value = "错误信息")
    private String message;

    /* getter/setter */

}

看完本文有收获?请转发分享给更多人


欢迎关注“JAVA乐园”,我们分享最有价值的互联网技术干货文章,助力您成为有思想的全栈架构师,我们只聊互联网、只聊架构!打造最有价值的架构师圈子和社区。

  • 长按下方的二维码可以快速关注我们

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

BUG弄潮儿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值