引入pom
<dependency><groupId>io.springfox</groupId><artifactId>springfox-boot-starter</artifactId><version>3.0.0</version></dependency>
配置
import io.swagger.models.auth.In;
import io.swagger.v3.oas.annotations.Operation;
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.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import java.util.ArrayList;
import java.util.List;@Configuration
public class SwaggerConfig
{/*** 安全模式,这里指定token通过Authorization头请求头传递*/private List<SecurityScheme> securitySchemes(){List<SecurityScheme> apiKeyList = new ArrayList<SecurityScheme>();apiKeyList.add(new ApiKey("Authorization", "Authorization", In.HEADER.toValue()));apiKeyList.add(new ApiKey("Head", "Head", In.HEADER.toValue()));apiKeyList.add(new ApiKey("Query", "Query", In.QUERY.toValue()));return apiKeyList;}/*** 安全上下文*/private List<SecurityContext> securityContexts(){List<SecurityContext> securityContexts = new ArrayList<>();securityContexts.add(SecurityContext.builder().securityReferences(defaultAuth()).operationSelector(o -> o.requestMappingPattern().matches("/.*")).build());return securityContexts;}/*** 默认的安全上引用*/private List<SecurityReference> defaultAuth(){AuthorizationScope[] authorizationScopes ={new AuthorizationScope("global", "accessEverything")} ;List<SecurityReference> securityReferences = new ArrayList<>();securityReferences.add(new SecurityReference("Authorization", authorizationScopes));securityReferences.add(new SecurityReference("Head", authorizationScopes));securityReferences.add(new SecurityReference("Query", authorizationScopes));return securityReferences;}@Beanpublic Docket swagger3() {return new Docket(DocumentationType.OAS_30).select().apis(RequestHandlerSelectors.withMethodAnnotation(Operation.class)).paths(PathSelectors.regex("/test.*")).build().groupName("swagger3.0").securitySchemes(securitySchemes()).securityContexts(securityContexts()).apiInfo(apiInfo());}/*** 添加摘要信息*/private ApiInfo apiInfo(){// 用ApiInfoBuilder进行定制return new ApiInfoBuilder()// 设置标题.title("标题:XXX系统_接口文档")// 描述.description("描述:xxxx.")// 作者信息.contact(new Contact("作者信息", null, null))// 版本.version("版本号: >...>").build();}
}
可以加上全局请求参数
对象
ReqSwagger3VO
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;import java.io.Serializable;
import java.util.List;@Data
@Schema(name="ReqSwagger3VO",description ="swagger3对象" )
public class ReqSwagger3VO implements Serializable {private static final long serialVersionUID = 646541L;@Schema(description = "字符串",example = "aaaa")private String dataStr;@Schema(description = "数字",example = "1111")private Integer dataInt;@Schema(description = "字符数组" )private List<String> listStr;@Schema(description = "数字数组")private List<Integer> listInt;@Schema(description = "用户")private User user;@Schema(description = "用户数组")private List<User> userList;@Schema(hidden = true)private String hiddenStr;private String hiddenNotStr;
}
User
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Data;
//https://www.cnblogs.com/antLaddie/p/17418078.html
@Schema(description ="用户信息" )
@Data
@AllArgsConstructor
public class User {@Schema(description = "姓名",example = "张三")private String name;@Schema(description = "年龄",example = "18", format = "int32")private int age;@Schema( description = "学生分数属性", format = "double", example = "55.50")private Double fraction;
}
控制层
example 赋值问题还没解决
import io.swagger.v3.oas.annotations.Hidden;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.StringWriter;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;@RestController
@RequestMapping("/test/swagger")
@Tag(name = "接口类描述name",description = "接口类描述desc")
public class SwaggerController {@Operation(summary = "get请求")@GetMapping("{pathParam}/get")public Object get(@Parameter(description="reqParam参数描述", schema = @Schema(allowableValues = {"aaa", "22222"}))@RequestParam String reqParam,@Parameter(description="pathParam参数描述",example = "111")@PathVariable Integer pathParam,@Parameter(description="headParam参数描述", schema = @Schema(allowableValues = {"888888"}))@RequestHeader Long headParam){return null;}@Operation(summary = "get2请求,example赋值不生效",parameters={@Parameter(ref="reqParam",name = "reqParam",description="reqParam参数描述",in= ParameterIn.QUERY, schema = @Schema(allowableValues = {"aaa", "22222"})),@Parameter(ref="pathParam", name = "pathParam",description="pathPatam参数描述",in= ParameterIn.PATH,schema = @Schema(allowableValues = {"11111", "333"})),@Parameter(ref="headParam", name = "headParam",description="headParam参数描述",in= ParameterIn.PATH,schema = @Schema(allowableValues = {"11111", "333"}))})@GetMapping("/2/{pathParam}/get")public Object get2(@RequestParam String reqParam,@PathVariable Integer pathParam ,@RequestHeader Long headParam){return null;}@Operation(summary = "post请求")@PostMapping("/post")public Object post(@RequestBody ReqSwagger3VO reqSwaggerVO){return null;}@Hidden@PostMapping("/hidden")public Object hidden(@RequestBody ReqSwaggerVO reqSwaggerVO){return null;}@Operation(summary = "文件上传")@PostMapping(value = "/upload")public Object uploadFile(@RequestParam(value = "file") @RequestPart MultipartFile file){return null;}@Operation(summary = "zip下载")@PostMapping(value = "/zip/download")public void downloadZip(HttpServletResponse response)throws Exception {String fileName ="file.zip";ByteArrayOutputStream outputStream = new ByteArrayOutputStream();ZipOutputStream zip = new ZipOutputStream(outputStream);for (int i = 0; i < 2; i++) {StringWriter sw = new StringWriter();sw.append("11111a"+i);sw.append("2222c"+i);// 添加到zipzip.putNextEntry(new ZipEntry(i+"name.txt"));IOUtils.write(sw.toString(), zip, "UTF-8");IOUtils.close(sw);zip.flush();zip.closeEntry();}IOUtils.close(zip);byte[] data = outputStream.toByteArray();response.reset();response.addHeader("Access-Control-Allow-Origin", "*");response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");response.setHeader("Content-Disposition", "attachment; filename=\""+fileName+"\"");response.addHeader("Content-Length", "" + data.length);response.setContentType("application/octet-stream; charset=UTF-8");IOUtils.write(data, response.getOutputStream());}}