如何在springboot中集成swagger,相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
<!-- 引入 swagger等相關依賴 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.6.1</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.6.1</version> </dependency>
package com.sailing.springbootmybatis.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.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; /** * @author baibing * @project: springboot-mybatis * @package: com.sailing.springbootmybatis.config * @Description: swagger2配置類 * @date 2018/9/25 15:35 */ @Configuration @EnableSwagger2 public class Swagger2Config { @Bean public Docket createRestApi(){ return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.sailing.springbootmybatis.controller")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo(){ return new ApiInfoBuilder() .title("SPRING-BOOT整合MYBATIS--API說明文檔") .description("2018-8完成版本") .contact("Sailing西安研發中心-baibing") .version("1.0") .license("署名-非商用-相同方式共享 4.0轉載請保留原文鏈接及作者") .licenseUrl("https://creativecommons.org/licenses/by-nc-sa/4.0/") .build(); } }
package com.sailing.springbootmybatis.controller; import com.sailing.springbootmybatis.bean.Userinfo; import com.sailing.springbootmybatis.common.log.LogOperationEnum; import com.sailing.springbootmybatis.common.log.annotation.MyLog; import com.sailing.springbootmybatis.common.response.BuildResponseUtil; import com.sailing.springbootmybatis.common.response.ResponseData; import com.sailing.springbootmybatis.common.websocket.WebSocketServer; import com.sailing.springbootmybatis.service.RedisService; import com.sailing.springbootmybatis.service.UserinfoService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import springfox.documentation.annotations.ApiIgnore; import javax.validation.Valid; import java.io.IOException; import java.util.List; /** * @author baibing * @project: springboot-mybatis * @package: com.sailing.springbootmybatis.controller * @Description: Userinfo controller 控制層 * @date 2018/9/12 10:07 */ @RestController @Api(value = "USERINFO", description = "用戶信息測試controller") public class UserinfoController{ @Autowired private UserinfoService userinfoService; @Autowired private WebSocketServer webSocketServer; @Autowired private RedisService redisService; /** * 查找指定id對應的用戶 * @param id * @return */ @RequestMapping(value = "/user/{id}", method = RequestMethod.GET) @MyLog(type = LogOperationEnum.SELECT,value = "查詢指定id的用戶信息") @ApiOperation(value = "查詢指定id的用戶信息接口", notes = "查詢指定id的用戶信息接口") public ResponseData getUser(@PathVariable(value = "id") Integer id){ return userinfoService.findById(id); } /** * 查找所有用戶 * @return */ @RequestMapping(value = "/users", method = RequestMethod.GET) @MyLog(type = LogOperationEnum.SELECT,value = "查詢全部用戶信息") @ApiOperation(value = "查詢所有用戶信息接口", notes = "查詢所有用戶信息接口") public ResponseData getAllUsers(){ return userinfoService.findAllUsers(); } /** * 查找所有用戶(帶分頁) * @param page 當前頁數 * @param rows 每頁顯示條數 * @return */ @RequestMapping(value = "/users/p", method = RequestMethod.GET) @ApiOperation(value = "查詢所有用戶信息接口(帶分頁)", notes = "查詢所有用戶信息接口(帶分頁)") public ResponseData getAllUsers(Integer page, Integer rows){ return userinfoService.findAllUsers(page, rows); } /** * 新增用戶 (帶參數校驗@Valid) * 注意:BindingResult 對象必須在 @Valid 的緊挨著的后面,否則接收不到錯誤信息 * @Valid 可以校驗json 也可以校驗表單傳遞的對象屬性 * @param userinfo * @return */ @RequestMapping(value = "/user", method = RequestMethod.POST) @MyLog(type = LogOperationEnum.INSERT, value = "新增用戶信息") @ApiOperation(value = "新增用戶接口(包含參數校驗)", notes = "新增用戶接口(包含參數校驗)") public ResponseData saveUserinfo(@RequestBody @Valid Userinfo userinfo, BindingResult bindingResult){ if(bindingResult.hasErrors()){ return BuildResponseUtil.buildFailResponse(bindingResult.getFieldError().getDefaultMessage()); } return userinfoService.saveUser(userinfo); } /** * 刪除指定用戶 * @param id 用戶id * @return */ @RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE) @ApiOperation(value = "刪除指定id的用戶信息接口", notes = "刪除指定id的用戶信息接口") public ResponseData deleteUser(@PathVariable Integer id){ return userinfoService.deleteUser(id); } /** * 更新用戶 * @param userinfo * @return */ @RequestMapping(value = "/user", method = RequestMethod.PUT) @ApiOperation(value = "更新指定id用戶信息接口", notes = "更新指定id用戶信息接口") public ResponseData updateUserinfo(@RequestBody Userinfo userinfo){ return userinfoService.updateUser(userinfo); } /** * 給指定用戶推送消息 * @param userName 用戶名 * @param message 消息 * @throws IOException */ @RequestMapping(value = "/socket", method = RequestMethod.GET) @ApiIgnore //使用此注解忽略方法的暴露,也可以用在controller上 @ApiOperation(value = "給指定用戶推送socket消息接口", notes = "給指定用戶推送socket消息接口") public void testSocket(@RequestParam String userName,@RequestParam String message){ webSocketServer.sendInfo(userName, message); } /** * 測試redis接口保存String類型action * @param address * @return */ @RequestMapping(value = "/redis", method = RequestMethod.POST) @ApiIgnore //使用此注解忽略方法的暴露,也可以用在controller上 @ApiOperation(value = "redis中添加String數據接口", notes = "redis中添加String數據接口") public ResponseData setString(@RequestBody String address){ System.out.println(address); return redisService.setValue(address); } /** * 測試redis接口保存實體類型action * @param userinfo * @return */ @RequestMapping(value = "/redis/userinfo", method = RequestMethod.POST) @ApiIgnore //使用此注解忽略方法的暴露,也可以用在controller上 @ApiOperation(value = "redis中添加Userinfo實體接口", notes = "redis中添加Userinfo實體接口") public ResponseData setEntity(@RequestBody Userinfo userinfo){ return redisService.setEntityValue(userinfo); } /** * 測試redis接口讀取實體類型action * @param key * @return */ @RequestMapping(value = "/redis/userinfo/{key}", method = RequestMethod.GET) @ApiIgnore //使用此注解忽略方法的暴露,也可以用在controller上 @ApiOperation(value = "redis中讀取指定key對應的數據接口", notes = "redis中讀取指定key對應的數據接口") public ResponseData getEntity(@PathVariable String key){ return redisService.getEntityValue(key); } /** * * @param list * @return */ @RequestMapping(value = "/redis/userList", method = RequestMethod.POST) @ApiIgnore //使用此注解忽略方法的暴露,也可以用在controller上 @ApiOperation(value = "redis中添加包含Userinfo實體的集合接口", notes = "redis中添加包含Userinfo實體的集合接口") public ResponseData setCollection(@RequestBody List<Userinfo> list){ return redisService.setCollectionValue(list); } /** * 測試redis接口讀取實體類型action * @param key * @return */ @RequestMapping(value = "/redis/userList/{key}", method = RequestMethod.GET) @ApiOperation(value = "redis中讀取指定key對應的集合數據接口", notes = "redis中讀取指定key對應的集合數據接口") public ResponseData getCollection(@PathVariable String key){ return redisService.getCollectionValue(key); } }
訪問 http://127.0.0.1:端口/項目路徑/swagger-ui.html 就ok了, 頁面如下:
swagger-ui界面展示
百思不得其解,但是可以肯定的是加了什么配置導致,最后在application.yml 中發現了一個配置:
spring.mvv.resources.add-mapping:false
將其注釋掉熟悉的界面又回來了,查閱資料發現這個配置是不自動給靜態資源添加路徑,導致swagger-ui.html找不到資源,知道原因后摸索看能不能在保留以上配置的前提下自己手動給swagger-ui.html添加靜態資源路徑呢?
package com.sailing.springbootmybatis.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /** * 在SpringBoot2.0及Spring 5.0 WebMvcConfigurerAdapter已被廢棄,目前找到解決方案就有 * 1 直接實現WebMvcConfigurer (官方推薦) * 2 直接繼承WebMvcConfigurationSupport * @ https://blog.csdn.net/lenkvin/article/details/79482205 */ @Configuration public class WebMvcConfig extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("swagger-ui.html") .addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/"); } }
看完上述內容,你們掌握如何在springboot中集成swagger的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。