一直以來作對外的接口文檔都比較原始,基本上都是手寫的文檔傳來傳去,最近發現了一個新玩具,能夠在接口上省去很多麻煩。html
swagger是一款方便展現的API文檔框架。它能夠將接口的類型最全面的展現給對方開發人員,避免了手寫文檔的片面和偏差行爲。git
swagger目前有兩種swagger和swagger2兩種,1比較麻煩,因此不考慮使用。本文主要記錄我用swagger2作對外接口的兩種方式,方面後面查閱。github
一、maven依賴web
<!--springfox依賴--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.8.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.6.3</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.6.3</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.4.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.4.0</version> </dependency>
二、spring-mvc.xml 中添加映射靜態的配置(其實我項目中把這個去掉也能夠,不知道什麼狀況):spring
<!-- swagger靜態文件路徑 --> <mvc:resources location="classpath:/META-INF/resources/" mapping="swagger-ui.html"/> <mvc:resources location="classpath:/META-INF/resources/webjars/" mapping="/webjars/**"/>
注意:基本的springmvc配置我就不貼了,須要注意的是,若是你看到swagger-ui.html 界面出來,但卻一片空白,請檢查下你web.xml中攔截器的配置,必定要springmvc先攔截到,而後界面纔會顯示的。api
三、而後是swagger2的配置類:spring-mvc
@Configuration @EnableSwagger2 public class SwaggerConfig extends WebMvcConfigurationSupport { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("net.laoyeyey.yyblog")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("yyblog項目 RESTful APIs") .description("yyblog項目api接口文檔") .version("1.0") .build(); } }
注意:paths若是在生產狀況下能夠調整爲PathSelectors.none(),即不顯示全部接口信息;springboot
四、接口信息配置restful
即在SpringMvc的Controller中配置相關的接口信息mvc
@Controller @RequestMapping(value = "aitou") @Api(description = "測試服務-帳戶信息查詢") public class DailyOperationDataController { Logger logger = Logger.getLogger(DailyOperationDataController.class); @Autowired private DailyOperationDataService DailyOperationDataService; /*
* @ApiOperation(value = "接口說明", httpMethod ="接口請求方式", response ="接口返回參數類型", notes ="接口發佈說明"
* @ApiParam(required = "是否必須參數", name ="參數名稱", value ="參數具體描述"
*/ @ApiOperation(value = "帳戶信息查詢接口") @RequestMapping(method ={RequestMethod.POST,RequestMethod.GET}, value="/query/dailydata/{dataDate}") @ResponseBody public DailyOperationDataDto getDailyReportByDataDate(@PathVariable("dataDate") String dataDate) { try { return DailyOperationDataService.getDailyReportByDataDate(dataDate); } catch (Exception e) { logger.error(e.getMessage(), e); } return null; } }
注:一般狀況下swagger2會將掃描包下全部的接口展現出來,這裏我是對外的接口是單獨一個包,避免展現過多的接口,固然接口方法也可讓它不展現。能夠在下面看到相關的註解中有寫。
經常使用的一些註解
@Api:用在類上,說明該類的做用
@ApiOperation:用在方法上,說明方法的做用
@ApiImplicitParams:用在方法上包含一組參數說明
@ApiImplicitParam:用在 @ApiImplicitParams 註解中,指定一個請求參數的各個方面
paramType:參數放在哪一個地方
· header --> 請求參數的獲取:@RequestHeader
· query -->請求參數的獲取:@RequestParam
· path(用於restful接口)--> 請求參數的獲取:@PathVariable
· body(不經常使用)
· form(不經常使用)
name:參數名
dataType:參數類型
required:參數是否必須傳
value:參數的意思
defaultValue:參數的默認值
@ApiResponses:用於表示一組響應
@ApiResponse:用在@ApiResponses中,通常用於表達一個錯誤的響應信息
code:數字,例如400
message:信息,例如"請求參數沒填好"
response:拋出異常的類
@ApiParam:單個參數描述
@ApiModel:描述一個Model的信息,用對象來接收參數(這種通常用在post建立的時候,使用@RequestBody這樣的場景,請求參數沒法使用@ApiImplicitParam註解進行描述的時候)
@ApiModelProperty:描述一個model的屬性
@ApiProperty:用對象接收參數時,描述對象的一個字段
@ApiIgnore:使用該註解忽略這個API
基本上就是上面這些了,是否是很easy,下面看下效果圖
上面說了使用傳統的springmvc整合swagger2,在說說最近比較流行的springboot的方式,其實原理都是同樣的。
一、maven依賴
<!--springfox依賴 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.7.0</version> </dependency>
這個是我最近用springboot寫的我的項目中的內用,版本用的2.7.0
二、添加靜態資源配置
@Configuration public class WebMvcConfig extends WebMvcConfigurerAdapter {/** * 配置靜態資源路徑以及上傳文件的路徑 * * @param registry */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/"); registry.addResourceHandler("/upload/**").addResourceLocations(environment.getProperty("spring.resources.static-locations")); /*swagger-ui*/ registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); } }
其實就是最後兩句,若是你不配置這個的話,訪問swagger-ui.html會出現500,仍是404的錯誤來着,記不清了,應該是404.
三、swagger2的配置類
和上面同樣,基本上沒區別
@Configuration @EnableSwagger2 @EnableWebMvc public class SwaggerConfig extends WebMvcConfigurationSupport { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("net.laoyeye.yyblog.web.frontend")) .paths(PathSelectors.none()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("yyblog項目 RESTful APIs") .description("yyblog項目api接口文檔") .version("1.0") .build(); } }
注意,我上面有說path的問題哦,直接拷貝不顯示api的,(#^.^#)
四、接口的配置
/** * 前臺文章Controller * @author 小賣鋪的老爺爺 * @date 2018年5月5日 * @website www.laoyeye.net */ @Api(description="文章查詢") @Controller @RequestMapping("/article") public class ArticleController { @Autowired private ArticleService articleService; @Autowired private SettingService settingService; @Autowired private CateService cateService; @Autowired private TagReferService tagReferService; @Autowired private UserService userService; @Autowired private ArticleMapper articleMapper; @Autowired private CommentService commentService; @ApiOperation(value="文章查詢接口") @ApiImplicitParam(name = "id", value = "文章ID", required = true, dataType = "Long") @GetMapping("/{id}") public String index(Model model, @PathVariable("id") Long id) { try { articleService.updateViewsById(id); } catch (Exception ignore) { } List<Setting> settings = settingService.listAll(); Map<String,Object> map = new HashMap<String,Object>(); for (Setting setting : settings) { map.put(setting.getCode(), setting.getValue()); } Article article = articleService.getArticleById(id); model.addAttribute("settings", map); model.addAttribute("cateList", cateService.listAllCate()); model.addAttribute("article", article); model.addAttribute("tags", tagReferService.listNameByArticleId(article.getId())); model.addAttribute("author", userService.getNicknameById(article.getAuthorId())); //回頭改 model.addAttribute("articles", articleMapper.listArticleByTitle(null)); model.addAttribute("similars", articleMapper.listArticleByTitle(null)); CommentQuery query = new CommentQuery(); query.setLimit(10); query.setPage(1); query.setArticleId(id); model.addAttribute("comments", commentService.listCommentByArticleId(query)); return "frontend/article"; } @ApiOperation(value="文章評論查詢接口") @PostMapping("/comments") @ResponseBody public DataGridResult comments(CommentQuery query) { //設置默認10 query.setLimit(10); return commentService.listCommentByArticleId(query); } @ApiOperation(value="文章點贊接口") @ApiImplicitParam(name = "articleId", value = "文章ID", required = true, dataType = "Long") @PostMapping("/approve") @ResponseBody public YYBlogResult approve(@RequestParam Long articleId) { return articleService.updateApproveCntById(articleId); } }
最後一樣來個效果圖,和上面同樣。
PathSelectors.none()的時候
![](http://static.javashuo.com/static/loading.gif)
PathSelectors.any()的時候
![](http://static.javashuo.com/static/loading.gif)
![](http://static.javashuo.com/static/loading.gif)
看到效果圖是否是接口內容一目瞭然,很簡潔明瞭了。
最後,好像忘記說swagger文檔的路徑了
若是你的項目在根目錄:http://localhost:8080/swagger-ui.html
若是不是根目錄那就是:http://localhost:8080/你的項目名/swagger-ui.html
實例地址:http://www.laoyeye.net/management/index 帳號/密碼:test/123456 菜單:系統設置/接口文檔