废话不介绍,简单说就是为了暴露接口文档,方便测试。
在pom文件中引入swagge相关依赖
<!--添加Swagger依赖 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!--添加Swagger-UI依赖 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
添加配置
package com.sonngfayuan.config;
import io.swagger.annotations.ApiOperation;
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;
/**
* <p>
* Swagger配置
* </p>
*
* @author songfayuan
* @date 2021/10/20 8:08 下午
*/
@Configuration //声明该类为配置类
@EnableSwagger2 //声明启动Swagger2
public class SwaggerConfig {
@Bean
public Docket customDocket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
// .apis(RequestHandlerSelectors.basePackage("com.sonngfayuan"))//扫描的包路径
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))//扫描的包路径
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("LearnDemo Swagger API ")
.description("XXX接口文档")
.termsOfServiceUrl("https://songfayuan.blog.csdn.net/")
.contact(new Contact("宋发元CSDN","https://songfayuan.blog.csdn.net/","1414798079@qq.com"))
.version("1.0")
.build();
}
}
Swagger使用案例SwaggerDemoController
package com.sonngfayuan.learn;
import cn.hutool.json.JSONObject;
import com.sonngfayuan.utils.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
/**
* <p>
* Swagger使用案例
* <p>
* =====================start=====================
* 说明:
*
* @author songfayuan
* @ApiImplicitParams({
* @ApiImplicitParam(name = "id", value = "项目ID", dataType = "String", paramType = "query", required = true),
* @ApiImplicitParam(name = "useridlist", value = "用户ID数组", dataType = "String", paramType = "body", allowMultiple = true, required = true ),
* @ApiImplicitParam(name = "Authorization", value = "身份验证Token", dataType = "String", paramType = "header"),
* })
* <p>
* allowMultiple=true————表示是数组格式的参数
* dataType="body"————表示数组中参数的类型
* <p>
* dataType="String" 代表请求参数类型为String类型,当然也可以是Map、User、int等;
* paramType="body" 代表参数应该放在请求的什么地方:
* <p>
* header-->放在请求头。请求参数的获取:@RequestHeader(代码中接收注解)
* query -->用于get请求的参数拼接。请求参数的获取:@RequestParam(代码中接收注解)
* path -->(用于restful接口)-->请求参数的获取:@PathVariable(代码中接收注解)
* body -->放在请求体。请求参数的获取:@RequestBody(代码中接收注解)
* form -->(不常用)
* =====================end=====================
* </p>
* @date 2021/10/20 9:10 下午
*/
@Api(tags = "Swagger使用案例")
@RestController
@RequestMapping("/demo")
public class SwaggerDemoController {
@GetMapping("/swaggerDemo")
@ApiOperation("swagger使用案例") //描述方法的用途
@ApiImplicitParam(name = "params", value = "参数具体意义", defaultValue = "参数默认值", dataType = "String", paramType = "query")
public Response swaggerDemo(String params) {
return Response.success(params);
}
@PostMapping("/addInfo")
@ApiOperation("添加用户的接口")
@ApiImplicitParams({
@ApiImplicitParam(name = "Authorization", value = "身份验证Token", defaultValue = "token", dataType = "String", paramType = "header"),
@ApiImplicitParam(name = "id", value = "项目ID", defaultValue = "110", dataType = "int", paramType = "query", required = true),
@ApiImplicitParam(name = "address", value = "用户地址", defaultValue = "深圳", paramType = "query", required = true),
@ApiImplicitParam(name = "userIdlist", value = "用户ID数组", defaultValue = "[1,2,3]", dataType = "String", paramType = "body", allowMultiple = true, required = true)
})
public Response addInfo(@RequestHeader String Authorization, @RequestParam Integer id, @RequestParam String address, @RequestBody String[] userIdlist) {
return Response.success("请求成功");
}
@GetMapping("/getOneInfo/{id}")
@ApiOperation("根据id查询信息")
@ApiImplicitParam(name = "id", value = "用户id", defaultValue = "110", dataType = "int", paramType = "path", required = true)
public Response getOneInfo(@PathVariable Integer id) {
return Response.success(id);
}
@PutMapping("/editInfo")
@ApiOperation("更新信息")
@ApiImplicitParam(name = "jsonObject", value = "用户信息", defaultValue = "{}", dataType = "JSONObject", paramType = "body", required = true)
public Response editInfo(@RequestBody JSONObject jsonObject) {
return Response.success(jsonObject);
}
}
工具类Response
/*
* Copyright (c) 2018-2025, songfayuan All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the 霖梓控股 developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: songfayuan (1414798079@qq.com)
*/
package com.sonngfayuan.utils;
import java.io.Serializable;
/**
* 响应信息主体
*
* @param <T>
* @author songfayuan
*/
//@JsonInclude(JsonInclude.Include.NON_NULL)
public class Response<T> implements Serializable {
private static final long serialVersionUID = 1L;
private static final int SUCCESS_CODE = 200;
private static final String SUCCESS_MSG = "success";
private static final int ERROR_CODE = 500;
private static final String ERROR_MSG = "服务器内部异常,请联系技术人员"; //将error改成了内容信息
public static final int NO_LOGIN = -1;
public static final int SUCCESS = 200;
public static final int FAIL = 500;
public static final int NO_PERMISSION = 2;
private String msg = "success";
private int code = SUCCESS;
private T data;
public Response() {
super();
}
public Response(T data) {
super();
this.data = data;
}
public Response(T data, String msg) {
super();
this.data = data;
this.msg = msg;
}
public Response(int code, T data, String msg) {
super();
this.code = code;
this.data = data;
this.msg = msg;
}
public Response(int code, String msg) {
super();
this.code = code;
this.msg = msg;
}
public Response(Throwable e) {
super();
this.msg = e.getMessage();
this.code = FAIL;
}
public static Response success() {
Response resp = new Response();
resp.code = (SUCCESS_CODE);
resp.msg = (SUCCESS_MSG);
return resp;
}
public static Response successResponse(String msg) {
Response resp = new Response();
resp.code = SUCCESS_CODE;
resp.msg = msg;
return resp;
}
public static Response error() {
Response resp = new Response();
resp.code = (ERROR_CODE);
resp.msg = (ERROR_MSG);
return resp;
}
public static Response errorResponse(String msg) {
Response resp = new Response();
resp.code = ERROR_CODE;
resp.msg = msg;
return resp;
}
public static Response response(int code, String msg) {
Response resp = new Response();
resp.code = (code);
resp.msg = (msg);
return resp;
}
public static Response response(int code, String msg, Object data) {
Response resp = new Response();
resp.code = (code);
resp.msg = (msg);
resp.data = data;
return resp;
}
public static Response success(Object data) {
Response resp = new Response();
resp.code = (SUCCESS_CODE);
resp.msg = (SUCCESS_MSG);
resp.data = data;
return resp;
}
public static Response error(Object data) {
Response resp = new Response();
resp.code = (ERROR_CODE);
resp.msg = (ERROR_MSG);
resp.data = data;
return resp;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
访问swagger-ui
启动项目,访问http://localhost:8080/swagger-ui.html

测试

本文档介绍了如何在SpringBoot项目中集成Swagger2,通过添加相关依赖和配置,实现API接口的自动化文档展示。SwaggerDemoController展示了Swagger的使用,包括不同类型的参数注解和接口测试。
1422

被折叠的 条评论
为什么被折叠?



