Spring Boot筆記(一) springboot 集成 swagger-ui


個人博客網:https://wushaopei.github.io/    (你想要這里多有)

1、添加依賴

                <!--SpringBoot整合Swagger-ui-->
                <dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>2.9.2</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger-ui</artifactId>
			<version>2.9.2</version>
		</dependency>

2、設置配置類


package com.example.poiutis.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; /** * @ClassName SwaggerConfig * @Description TODO * @Author wushaopei * @Date 2019/7/22 16:05 * @Version 1.0 */ // 啟動時加載類 @Configuration // 啟用Swagger API文檔 @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() // 自行修改為自己的包路徑 .apis(RequestHandlerSelectors.basePackage("com.example.poiutis.controller")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("報表管理") .description("報表管理中心 API 1.0 操作文檔") //服務條款網址 .termsOfServiceUrl("https://blog.csdn.net/weixin_42405670") .version("1.0") .contact(new Contact("鮀城小帥", "https://blog.csdn.net/weixin_42405670", "15989746839@163.com")) .build(); } }
3、啟動類加上注解@EnableSwagger
啟動該注解使得用在controller中的swagger注解生效,覆蓋的范圍下的所有controller

4、Controller 類配置

@Api的使用

API作用在Controller,作為swagger文檔資源,該注解將一個controller標注為一個Swagger資源(API). 在默認情況下,Swagger-Core 只會掃描解析具有 @Api 注解的類,而會自動忽略其他類別資源(JAX-RS endpoints、Servlets 等)的注解。

@ApiOperation 的使用

ApiOperation 定義在方法上,描述方法名、方法解釋、返回信息、標記等信息。


/** * 發票管理 * @author issuser * */ @Api(value = "發票",description = "發票操作 API", position = 100, protocols = "http") @RestController @RequestMapping(value = "/webcode") public class InvoiceController { private static Logger logger = LoggerFactory.getLogger(InvoiceController.class); @Autowired invoiceOrderService InvoiceOrderService; @ApiOperation(value = "導出操作日志到xls文件", notes = "需要登錄") @GetMapping("/exporInvoiceOrderXls") @ResponseBody public Object exporInvoiceOrderXls( HttpServletRequest request, HttpServletResponse response, @RequestParam(value="invoiceOrders")@ApiParam(value="invoiceOrders") List<String> invoiceOrders) { Map<String, Object> map = new HashMap<>(); response.setContentType("octets/stream"); Map<String, Object> map2 = new HashMap<String, Object>(); map2.put("sheetTitle", "消費記錄"); map2.put("header", new String[]{"訂單號", "商店名稱", "發票批次", "賬戶名稱", "商店地址", "刷卡賬號","商店電話","信用卡開戶行名稱"}); map2.put("fields", new String[]{"invoiceOrder", "companyName", "taxNumber", "accountBank", "companyAddress","bankNumber","companyTelephone","accountName"}); List<InvoiceOrder> invoiceOrderss = InvoiceOrderService.queryInvoiceLists(invoiceOrders,0,9999); map2.put("data",invoiceOrderss); List<Map<String, Object>> list = new ArrayList<>(); list.add(map2); String title = "日常消費刷卡發票記錄"; Map<String, short[]> mergedRegion = new HashMap<String, short[]>(); mergedRegion.put("通用標題名稱合並", new short[] {0, 0, 0, 100}); ExportExcel<InvoiceOrder> ex = new ExportExcel<>(); // 聲明一個工作薄 HSSFWorkbook workbook = new HSSFWorkbook(); // 生成一個標題樣式 HSSFCellStyle headerStyle = ex.cellStyle(workbook); // 生成一個內容樣式 HSSFCellStyle textStyle = ex.cellStyle(workbook); // 生成標題字體 ex.setFont(workbook, headerStyle, (short) 10, HSSFFont.BOLDWEIGHT_NORMAL); // 生成內容字體 ex.setFont(workbook, textStyle, HSSFFont.BOLDWEIGHT_NORMAL); try { OutputStream out = response.getOutputStream(); // 導出文件名稱添加當前時間 String date = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); //防止亂碼 // response.addHeader("Access-Control-Expose-Headers", "Content-Type,Content-Disposition"); // response.addHeader("Content-Disposition", // "attachment;filename=" + URLEncoder.encode(title, "GBK") + date // + ".xls"); response.setHeader("Content-Disposition", "attachment; filename=" + new String((title+".xls").getBytes("GB2312"),"ISO8859-1")); list.forEach(m -> { ExcelModel excelModel = new ExcelModel(); excelModel.setWorkbook(workbook); excelModel.setTitle(title); excelModel.setFields((String[]) m.get("fields")); excelModel.setHeader((String[]) m.get("header")); excelModel.setHeaderRow(2); excelModel.setMergedRegion(mergedRegion); excelModel.setHeaderStyle(headerStyle); excelModel.setTextStyle(textStyle); excelModel.setTitles((String) m.get("sheetTitle")); // 生成一頁表格 HSSFSheet sheet = workbook.createSheet((String) m.get("sheetTitle")); excelModel.setSheet(sheet); ex.exportExcel(excelModel, (Collection<InvoiceOrder>) m.get("data")); }); try { workbook.write(out); } catch (IOException e) { e.printStackTrace(); }finally { out.close(); } map.put("state","0"); map.put("message", "導出成功"); return map; } catch (IOException e) { e.printStackTrace(); map.put("state", "1"); map.put("message", e.getMessage()); return map; } } }
屬性名稱 備注
value url 的路徑值
tags 如果設置這個值,value 的值會被覆蓋
description  對 API 資源的描述
produces  For example, "application/json, application/xml"
consumes For example, "application/json, application/xml"
protocols Possible values: http, https, ws, wss
authorizations 高級特性認證時配置
hidden 配置為 true 將在文檔中隱藏
response 返回的對象
responseContainer 這些對象是有效的 "List", "Set" or "Map",其他無效
httpMethod "GET"、"HEAD"、"POST"、"PUT"、"DELETE"、"OPTIONS" and "PATCH"
code http 的狀態碼 默認 200
extensions 擴展屬性

@ApiImplicitParams 和 @ApiImplicitParam 的使用

@ApiImplicitParams 用於描述方法的返回信息,和 @ApiImplicitParam 注解配合使用;@ApiImplicitParam 用來描述具體某一個參數的信息,包括參數的名稱、類型、限制等信息。

5、啟動項目,進入API列表,localhost/swagger-ui.html#

完整springBoot 整合 Swagger 代碼 GitHub 鏈接地址:

注意問題:

出現以下問題時,要檢查SwaggerConfig 中配置的路徑是否正確;

即:

GitHub

6、Swagger常用注解

作用范圍 API 使用位置
協議集描述 @Api 用於 Controller 類上
協議描述 @ApiOperation 用在 Controller 的方法上
非對象參數集 @ApiImplicitParams 用在 Controller 的方法上
非對象參數描述 @ApiImplicitParam 用在 @ApiImplicitParams 的方法里邊
響應集 @ApiResponses 用在 Controller 的方法上
響應信息參數 @ApiResponse 用在 @ApiResponses 里邊
描述返回對象的意義 @ApiModel 用在返回對象類上
對象屬性 @ApiModelProperty 用在出入參數對象的字段上


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM