首页 > 学院 > 开发设计 > 正文

Spring Boot 使用Swagger2自动生成RESTful API文档

2019-11-08 20:14:34
字体:
来源:转载
供稿:网友
API文档自动生成工具有很多种,比如:SwaggerSPRing REST DocsRAMLApiDocJSSpringRestDoc这篇文章对这几种比较流行的API文档生成工具进行了评估和对比:https://opencredo.com/rest-api-tooling-review/

Swagger是属于比较推荐的一种。

Swagger的特点:1、在Spring Boot中配置非常简单2、项目部署时,根据代码自动生成文档,通过html展示3、代码改动后,项目重新部署时文档会自动更新,无需手动更新文档4、保证了代码和文档的一致性,不会出现不一致的情况5、可以直接在文档界面上测试接口,无需再利用第三方来调试接口了几个简单的步骤,就可以在Spring Boot中配置Swagger2来实现API文档自动生成:1、引入依赖:
		<!-- 文档自动生成 -->		<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>2、创建Swagger2配置类:
@Configuration@EnableSwagger2public class Swagger2 {	@Bean	public Docket createRestApi(){		return  new Docket(DocumentationType.SWAGGER_2)				.apiInfo(apiInfo())				.select()				.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))				.paths(PathSelectors.any())				.build();	}	private ApiInfo apiInfo(){		return new ApiInfoBuilder()				.title("专题页api文档")				.description("专题页api文档")				.termsOfServiceUrl("http://terms-of-services.url")				.version("1.0")				.build();	}}通过@Configuration注解,让Spring来加载该类配置;再通过@EnableSwagger2注解来启用Swagger2。apis()可以指定有某个注解的方法需要生成API文档,还可以指定扫描哪个包来生成文档,比如:
apis(RequestHandlerSelectors.basePackage("com.xjj.web.controller"))3、在Controller的方法中注解各种文档描述:
@RestController@RequestMapping("/topic/")public class TopicController {	protected final Logger logger = LoggerFactory.getLogger(this.getClass());	@Autowired	TopicService topicService;	@RequestMapping(value="getTopic", method = RequestMethod.GET)	@ApiOperation(value="接口描述。。。", response = TopicResult.class)	@ApiImplicitParams({			@ApiImplicitParam(name = "sn", value = "编号", required = true, dataType = "String", paramType = "query"),			@ApiImplicitParam(name = "token", value = "用户token", required = true, dataType = "String", paramType = "query")	})	public JsonResult getTopicBySn(HttpServletRequest request, @RequestParam String sn, @RequestParam String token){		JsonResult result = null;		try {			Topic topic = topicService.getTopic(sn);			if(topic == null){				result = new JsonResult(ReturnCode.PARAMS_ERROR, "错误");			}else {				result = new JsonResult(ReturnCode.SUCCESS, "成功", topic);			}		}catch (Exception e){			logger.error("getTopicBySn Exception", e);			result = new JsonResult(ReturnCode.EXCEPTION);		}		return result;	}}其中,response = TopicResult.class 表示返回值使用JsonResult的子类TopicResult来展示更详细的内容;如果不指定,则使用返回值JsonResult来生成文档。这两个类也需要相应的注解(@ApiModel和@ApiModelProperty):
@ApiModelpublic class JsonResult {	@ApiModelProperty(value = "状态码", example="40001", required = true, position=-2)	private String code;	@ApiModelProperty(value = "返回消息", example="恭喜,成功!", required = true, position=-1)	private String message;	@ApiModelProperty(value = "具体数据")	private Object data;	//constructors, getters, setters 略...}
@ApiModelpublic class TopicResult extends JsonResult {	@ApiModelProperty(value = "专题详情", required = true)	private Topic data;	//constructors, getters, setters 略...}对于里面的Topic类,也需要相应的@ApiModel和@ApiModelProperty注解(代码略)。对于Controller中的参数注解,也可以直接放到参数列表中,比如:
@RestController@RequestMapping("/apply/")public class ApplyController {	protected final Logger logger = LoggerFactory.getLogger(this.getClass());	@Autowired	ApplyService applyService;	@RequestMapping(value="store-mgr-setup", method = RequestMethod.POST)	@ApiOperation(value="接口描述")	public JsonResult applyStoreMgrSetup(HttpServletRequest request,					@ApiParam(value = "参数描述", required = true) @RequestBody DianApply dianApply){		JsonResult result = null;		//其他代码略...		return result;	}}4、API文档查看和调试项目启动后,访问这个url就可以看到自动生成的API文档了:http://localhost:8080/<project-name>/swagger-ui.html

测试:填入相应的参数后,点击下方“Try it out!”按钮,即可完成了一次请求调用!


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表