最近的一个新项目,在定义后端接口的时候,发现有些字段和接口名需要频繁的更改。以前的实现方式是定义一个wiki,通过wiki来描述接口,但是随着时间的流逝已经各种小的变更,wiki和实际的接口实现差别越来越大。基本到了一种不可维护的状态。
前一段时间在翻github的时候,正好看到swagger项目。搜索了一下,发现确实很不错,能很好的描述接口,遂决定在新项目中使用一下。
注:本文是基于springboot配置实现,但在实际中使用springmvc和本文的配置基本一致,不影响使用。
下面是第一种配置方式。尽量精简的配置。
一
1 在pom文件中引入依赖
<!-- Swagger --><dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.7.0</version></dependency><dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.7.0</version></dependency>
2 新建swag配置文件
在代码中新定义一个类,代码如下
@Configuration@EnableSwagger2public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.any()) .build() .apiInfo(apiInfo()); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("对外开放接口API 文档") .description("HTTP对外开放接口") .version("1.0.0") .termsOfServiceUrl("http://xxx.xxx.com") .license("LICENSE") .licenseUrl("http://xxx.xxx.com") .build(); }}
3 在自己的controller中使用
@Slf4j@RestControllerpublic class MyController { @RequestMapping(value = "hello", method = RequestMethod.GET) public String hello() { return "hello"; }}
如上的配置就可以了,下面是展示效果
在本地启动项目,然后浏览器输入:
http://localhost:8080/swagger-ui.html
注:本文内容来自互联网,旨在为开发者提供分享、交流的平台。如有涉及文章版权等事宜,请你联系站长进行处理。