写了一个工程,要写文档,相信所有的程序员都和我一样,最讨厌写文档,有没有片动生成文档的东西呢?有!
首先,我们要引入swagger。
1、swagger
什么是swagger?说白了,就是可以帮你生成一个可以测试接口的页面的工具。具体在这里:http://swagger.io/open-source-integrations/。多得我也不说了,文档很多,具体可以看这里:http://blog.sina.com.cn/s/blog_72ef7bea0102vpu7.html。说这个东西的的原因是,springfox是依赖这东西的。
2、springfox
为什么说springfox是依赖swagger的呢?因为swagger本身不支持spring mvc的,springfox把swagger包装了一下,让他可以支持springmvc。
我的项目是用spring-boot做的,基础知识就不在这里说了。只说怎么玩。
先是maven的引入:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>org.springframework.restdocs</groupId>
<artifactId>spring-restdocs-mockmvc</artifactId>
<version>1.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-staticdocs</artifactId>
<version>2.5.0</version>
<scope>test</scope>
</dependency>
我先写一个config类,看不懂的自己补下spring-boot:
package doc.base;
import lombok.extern.log4j.Log4j2;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.util.StopWatch;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
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;
import static springfox.documentation.builders.PathSelectors.*;
import static com.google.common.base.Predicates.*;
@Configuration
@EnableSwagger2//注意这里
@ComponentScan(basePackages = "doc")
@Log4j2
public class SwaggerConfig extends WebMvcConfigurerAdapter
implements EnvironmentAware {
/**
* 静态资源映射
*
* @param registry
* 静态资源注册器
*/
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
super.addResourceHandlers(registry);
}
@Override
public void setEnvironment(Environment environment) {//这里是从配置文件里读相关的字段
this.propertyResolver = new RelaxedPropertyResolver(environment,
"swagger.");
}
@Bean
public Docket swaggerSpringfoxDocket4KAD() {//最重要的就是这里,定义了/test/.*开头的rest接口都分在了test分组里,可以通过/v2/api-docs?group=test得到定义的json
log.debug("Starting Swagger");
StopWatch watch = new StopWatch();
watch.start();
Docket swaggerSpringMvcPlugin = new Docket(DocumentationType.SWAGGER_2)
.groupName("test")
.apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.any())
.paths(regex("/test/.*")) // and by paths
.build();
watch.stop();
log.debug("Started Swagger in {} ms", watch.getTotalTimeMillis());
return swaggerSpringMvcPlugin;
}
private ApiInfo apiInfo() {//这里是生成文档基本信息的地方
return new ApiInfo(propertyResolver.getProperty("title"),
propertyResolver.getProperty("description"),
propertyResolver.getProperty("version"),
propertyResolver.getProperty("termsOfServiceUrl"),
new Contact(propertyResolver.getProperty("contact.name"),
propertyResolver.getProperty("contact.url"),
propertyResolver.getProperty("contact.email")),
propertyResolver.getProperty("license"),
propertyResolver.getProperty("licenseUrl"));
}
private RelaxedPropertyResolver propertyResolver;
}
由于spring-mvc代理了/*,所以要把swagger-ui.html和/webjars/**做为静态资源放出来,不然无法访问。
然后,我们就可以在类上面加上swagger的注解了,只有这样,swagger才能生成文档:
@ApiOperation(
value = "get",
httpMethod = "GET",
response = String.class,
notes = "调用test get",
produces = MediaType.APPLICATION_JSON_VALUE)//这是接口的基本信息,不解释,自己看吧
@Snippet(
url = "/test/get",
snippetClass = MonitorControllerSnippet.Get.class)//这是我自己写的,方便spring-restdoc使用的,后面就说
@ApiImplicitParams({//这个是入参,因为入参是request,所以要在这里定义,如果是其它的比如spring或javabean入参,可以在参数上使用@ApiParam注解
@ApiImplicitParam(
name = "Service",
value = "服务",
required = true,
defaultValue = "monitor",
dataType = "String"),
@ApiImplicitParam(
name = "Region",
value = "机房",
required = true,
dataType = "String"),
@ApiImplicitParam(
name = "Version",
value = "版本",
required = true,
dataType = "String"),
@ApiImplicitParam(
name = "name",
value = "名称",
example = "kaddefault",
required = true,
dataType = "String"),
@ApiImplicitParam(
name = "producttype",
value = "产品类型",
example = "12",
required = true,
dataType = "int"),
@ApiImplicitParam(
name = "tags",
dataType = "String",
example = "{\"port\":8080}")
})
@RequestMapping(
path = "/test/get",
method = RequestMethod.GET)
public String get(HttpServletRequest request) {
log.debug("进入get");
return call4form(request);
}
然后我们调用一下http://localhost:8080/swagger-ui.html就可以看到了。
好了,我们现在可以用swagger-ui调试spring-mvc了,这只是第一步。
下面,我们要使用springfox生成文档。这里要使用swagger2markup来进行转换。
3、spring restdoc
spring restdoc就是生成例子用的。先用它把每一个接口都调用一遍,会生成一堆acsiidoc文件。但是如果一个一个调,就把代码写死了,于是我写了一个自定的注解去完成这个工作:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Snippet {
String httpMethod() default "GET";