SpringBoot集成swagger

我是研究僧i 提交于 2019-11-28 05:03:17

1、在pom.xml中引用swagger依赖包

io.springfox
springfox-swagger2
2.6.1


io.springfox
springfox-swagger-ui
2.6.1

2、创建swager配置类
package com.vk.liyj.config;

import io.swagger.annotations.ApiOperation;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

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;

/**

  • 类描述:配置swagger2信息
    */
    @Configuration // 让Spring来加载该类配置
    //@EnableWebMvc // 启用Mvc,非springboot框架需要引入注解@EnableWebMvc
    @EnableSwagger2 // 启用Swagger2
    public class Swagger2Config {
    @Bean
    public Docket createRestApi() {
    return new Docket(DocumentationType.SWAGGER_2)
    .apiInfo(apiInfo())
    .select()
    // 扫描指定包中的swagger注解
    // .apis(RequestHandlerSelectors.basePackage(“com.vk.liyj”))
    // 扫描所有有注解的api,用这种方式更灵活
    .apis(RequestHandlerSelectors
    .withMethodAnnotation(ApiOperation.class))
    .paths(PathSelectors.any()).build();
    }

private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title(“基础平台 RESTful APIs”)
.description(
“基础平台 RESTful 风格的接口文档,内容详细,极大的减少了前后端的沟通成本,同时确保代码与文档保持高度一致,极大的减少维护文档的时间。”)
.termsOfServiceUrl(“http://xiachengwei5.coding.me”)
.contact(“Xia”).version(“1.0.0”).build();
}
}

通过@Configuration注解,表明它是一个配置类,@EnableSwagger2开启swagger2。apiINfo()配置一些基本的信息。apis()指定扫描的包会生成文档。

3、编写swagger注解
package com.vk.liyj.model;

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

import java.util.Date;

import org.springframework.format.annotation.DateTimeFormat;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;

/**

  • 人员信息表 注解:@ApiModel 和 @ApiModelProperty 用于在通过对象接收参数时在API文档中显示字段的说明
  • 注解:@DateTimeFormat 和 @JsonFormat 用于在接收和返回日期格式时将其格式化 实体类对应的数据表为: user_info

*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties({ “handler”, “hibernateLazyInitializer” })
@ApiModel(value = “UserInfo”)
public class UserInfo {
@ApiModelProperty(value = “ID”)
private Integer id;

@ApiModelProperty(value = “用户登录账号”, required = true)
private String userNo;

@ApiModelProperty(value = “姓名”, required = true)
private String userName;

@ApiModelProperty(value = “姓名拼音”)
private String spellName;

@ApiModelProperty(value = “密码”, required = true)
private String password;

@ApiModelProperty(value = “手机号”, required = true)
private String userPhone;

@ApiModelProperty(value = “性别”)
private Integer userGender;

@ApiModelProperty(value = “记录创建时间”)
@DateTimeFormat(pattern = “yyyy-MM-dd HH:mm:ss”)
private Date createTime;

@ApiModelProperty(value = “记录修改时间”)
@DateTimeFormat(pattern = “yyyy-MM-dd HH:mm:ss”)
private Date updateTime;

@JsonFormat(locale = “zh”, timezone = “GMT+8”, pattern = “yyyy-MM-dd HH:mm:ss”)
public Date getCreateTime() {
return createTime;
}

@JsonFormat(locale = “zh”, timezone = “GMT+8”, pattern = “yyyy-MM-dd HH:mm:ss”)
public Date getUpdateTime() {
return updateTime;
}

}

4、控制器类
package com.vk.liyj.controller;

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

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.vk.liyj.model.UserInfo;
import com.vk.liyj.service.UserInfoService;

/**

  • 类描述:人员基本信息
    */
    @Controller
    @RequestMapping(value = “/userInfo”)
    @Api(value = “UserInfo”, description = "人员基本信息 ")
    public class UserInfoController {
    @Autowired
    UserInfoService service;
    @RequestMapping(value = “/selectAllUsers”, method = RequestMethod.GET)
    @ApiOperation(value = “查询所有的人员信息”, notes = “查询所有的人员信息”)
    public String selectAllUsers(HttpServletRequest request, HttpServletResponse response) {
    List userList = service.selectAllUsers();
    request.setAttribute(“userList”, userList);
    return “userList.jsp”;
    }
    @RequestMapping(value = “selectById”, method = RequestMethod.GET)
    @ApiOperation(value = “根据用户id查询用户详细信息”, notes = “根据用户id查询用户详细信息”)
    @ApiImplicitParams({
    @ApiImplicitParam(name = “type”, value = “类型(修改:update;默认为查看)”, required = false, paramType = “query”),
    @ApiImplicitParam(name = “id”, value = “用户id”, required = true, paramType = “query”)
    })
    public String selectById(HttpServletRequest request, HttpServletResponse response,
    @RequestParam(value = “id”) Integer id, @RequestParam(value = “type”) String type) {
    UserInfo user = service.selectByPrimaryKey(id);
    request.setAttribute(“user”, user);
    if(“update”.equals(type)) {
    return “userUpdate.jsp”;
    } else {
    return “userView.jsp”;
    }
    }
    @RequestMapping(value = “deleteById”, method = RequestMethod.GET)
    @ApiOperation(value = “根据用户id删除用户信息”, notes = “根据用户id删除用户信息”)
    @ApiImplicitParams({
    @ApiImplicitParam(name = “id”, value = “用户id”, required = true, paramType = “query”)
    })
    public String deleteById(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = “id”) Integer id) {
    int count = 0;
    try {
    count = service.deleteByPrimaryKey(id);
    if(count <=0 ) {
    return “error.jsp”;
    } else {
    request.getRequestDispatcher(“selectAllUsers”).forward(request, response);
    return “userList.jsp”;
    }
    } catch (Exception e) {
    e.getMessage();
    e.printStackTrace();
    return “error.jsp”;
    }
    }
    @RequestMapping(value = “add”, method = RequestMethod.POST)
    @ApiOperation(value = “添加用户信息”, notes = “添加用户信息”)
    public String add(HttpServletRequest request, HttpServletResponse response, UserInfo user) {
    int count = 0;
    try {
    count = service.insertSelective(user);
    if(count <=0 ) {
    return “error.jsp”;
    } else {
    //POST请求的方法不能直接转发到GET请求的方法,需要重定向
    response.sendRedirect(“selectAllUsers”);
    return “userList.jsp”;
    }
    } catch (Exception e) {
    e.getMessage();
    e.printStackTrace();
    return “error.jsp”;
    }
    }
    @RequestMapping(value = “update”, method = RequestMethod.POST)
    @ApiOperation(value = “根据用户id修改用户信息”, notes = “根据用户id修改用户信息”)
    public String update(HttpServletRequest request, HttpServletResponse response, UserInfo user) {
    int count = 0;
    try {
    count = service.updateByPrimaryKeySelective(user);
    if(count <=0 ) {
    return “error.jsp”;
    } else {
    //POST请求的方法不能直接转发到GET请求的方法,需要重定向
    response.sendRedirect(“selectAllUsers”);
    return “userList.jsp”;
    }
    } catch (Exception e) {
    e.getMessage();
    e.printStackTrace();
    return “error.jsp”;
    }
    }
    }

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

5、启动程序访问 http://localhost:8080/demo/swagger-ui.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!