Springboot集成Swagger2有这一篇就够了
最近公司需要集成Swagger API到已有服务,并导出文档给客户。此前的印象已经有点模糊,所以抽了点时间看了一下Swagger的源码,了解一下其实现原理,以及保存到文档以供其他人员阅读的办法。
Springboot集成Swagger2所需配置
maven依赖
<!--@EnableSwgger2注解及Swagger2Controller所在依赖包-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!--swagger-ui.html静态页面依赖包-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
配置类
@Configuration //标识配置类,用于Spring的配置自动扫描
@EnableSwagger2 //开启 Swagger2
@Order(1)
public class SwaggerConfig {
/**
* 配置 Swagger 的 Docket 的 Bean 实例
*
* @return
*/
@Bean
public Docket docket() {
Tag[] tags = new Tag[3];
tags[0] = new Tag("分类2","描述2");
tags[1] = new Tag("分类3","描述3");
tags[2] = new Tag("分类4","描述4");
return new Docket(DocumentationType.SWAGGER_2)
// 分组名
.groupName("All")
// api信息(文档描述、版本、作者信息、许可等)
.apiInfo(apiInfo())
.pathMapping("/")
// 分组中各接口按tags分成多个小的分组,对应@Api,@ApiOperation中的tags
// 若@Api,@ApiOperation的tags配置了这里的tag,则按tag将对应接口放到对应tag下
.tags(new Tag("分类1","描述1"),tags)
// 初始化一个ApiSelectorBuilder,此时的返回值已经不是Docket
.select()
// 路径过滤(例:屏蔽error相关api)
.paths(Predicates.not(PathSelectors.regex("/error.*")))
// 调用build方法由ApiSelectorBuilder转回Docket
.build();
}
//配置 Swagger信息=ApiInfo
private ApiInfo apiInfo() {
//作者信息
Contact contact = new Contact("Jeb", "http://hello.cn", "wujiangbao@fiberhome.com");
return new ApiInfo("Swagger API 文档", //文档标题
"这个是一个 Swagger 接口文档。", //文档描述
"v1.0", //文档版本
"http://team.cn", //队伍的网站地址
contact, //作者信息
"Apache 2.0", //许可证
"http://www.apache.org/licenses/LICENSE-2.0",//许可证Url
Collections.emptyList());
}
}
模型类配置示例
@ApiModel用于描述模型属性,@ApiModelProperties用于描述模型中的字段
package org.jeb.business.model;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.Date;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@AllArgsConstructor
// value为模型提供可选名称;若不配置,则模型名称为类名
@ApiModel(value = "模型名称", description = "人员")
public class Person {
@ApiModelProperty(value = "人员姓名",name="alias name", required = true, example = "1")
private String name;
@ApiModelProperty(value = "年龄", allowableValues = "range(1,100)", required = true, example = "1")
private Integer age;
@ApiModelProperty(value = "性别", allowableValues = "male,female", required = true, example = "male")
private String gender;
@ApiModelProperty(value = "生日", required = true, example = "1991-10-12")
private Date birthday;
}
Api接口配置示例
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import java.util.Date;
import java.util.Random;
import org.jeb.business.model.Person;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/person")
public class PersonController {
// 接口相关描述
@ApiOperation(value = "根据名称查询person",tags={"分类1"} )
@GetMapping("/getPersonByName")
// 接口参数相关描述
@ApiImplicitParams({
@ApiImplicitParam(name="name",value="姓名",type = "query")
})
public Person getPersonByName(@RequestParam String name) {
if (!name.isEmpty()) {
Random random = new Random();
return new Person(name, random.nextInt(100), "male", new Date(System.currentTimeMillis()));
} else {
return null;
}
}
@GetMapping("/world")
@ApiOperation(value="hello world", tags = {"分类3"})
public String world(@RequestParam String name) {
return "hello world " + name;
}
@ApiOperation(value="hello china", tags = {"分类2"})
@GetMapping("/China")
public String china() {
return "hello China";
}
}
swagger-ui静态页面效果
这里PersonController未配置@Api注解,但是PersonController中的接口配置了tags。Swagger自动将其添加了一个新分组,但是分组下没有接口。其下的接口按配置的tags放到了分组1,分组2,分组3
下面。
Spring对Swagger的bean初始化
刷新上下文 AbstractApplicationContext#refresh()
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");
// Prepare this context for refreshing.
// 准备上下文用于刷新
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
// 告诉子类去刷新内部bean工厂
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
// 为此上下文准备bean工厂
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
// 运行在上下文子类中对bean工厂做后处理
postProcessBeanFactory(beanFactory);
StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
// Invoke factory processors registered as beans in the context.
// 调用上下文中注册的工厂bean
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
// 注册拦截bean创建的处理器
registerBeanPostProcessors(beanFactory);
beanPostProcess.end();
// Initialize message source for this context.
// 初始化上下文的消息源
initMessageSource();
// Initialize event multicaster for this context.
// 初始化上下文的事件多播
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
// 初始化其他特定上下文子类中的特定bean
onRefresh();
// Check for listener beans and register them.
// 检查监听器bean,并注册他们
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
// 实例化所有剩余单例(非懒加载)
// swagger的Docket,Swagger2Controller,DocumentationPluginsBootstrapper均在此完成实例化
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
// 最后:完成上下文刷新,调用LifecycleProcessor的onRefresh()方法,发布上下文刷新结束事件
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
// 异常时销毁已经创建的单例,避免资源占用
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
contextRefresh.end();
}
}
}
完成上下文刷新,调用LifecycleProcessor的onRefresh()方法,发布上下文刷新结束事件
/**
* Finish the refresh of this context, invoking the LifecycleProcessor's
* onRefresh() method and publishing the
* {@link org.springframework.context.event.ContextRefreshedEvent}.
*/
@SuppressWarnings("deprecation")
protected void finishRefresh() {
// Clear context-level resource caches (such as ASM metadata from scanning).
clearResourceCaches();
// Initialize lifecycle processor for this context.
// 为上下文初始化生命周期处理器
initLifecycleProcessor();
// Propagate refresh to lifecycle processor first.
// 将刷新操作传递给生命周期处理器
// Spring这里getLifecycleProcessor()拿到的是DefaultLifecycleProcessor
getLifecycleProcessor().onRefresh();
// Publish the final event.
// 发布“上下文刷新完成”事件
publishEvent(new ContextRefreshedEvent(this));
// Participate in LiveBeansView MBean, if active.
if (!NativeDetector.inNativeImage()) {
LiveBeansView.registerApplicationContext(this);
}
}
DefaultLifecycleProcessor中就是简单的调用startBeans方法
@Override
public void onRefresh() {
startBeans(true);
this.running = true;
}
private void startBeans(boolean autoStartupOnly) {
// 获取实现了lifecycle接口的bean,swagger中对应的是DocumentationPluginsBootstrapper
Map<String, Lifecycle> lifecycleBeans = getLifecycleBeans();
Map<Integer, LifecycleGroup> phases = new TreeMap<>();
// 将lifecycle bean按phases分组
lifecycleBeans.forEach((beanName, bean) -> {
if (!autoStartupOnly || (bean instanceof SmartLifecycle && ((SmartLifecycle) bean).isAutoStartup())) {
int phase = getPhase(bean);
phases.computeIfAbsent(
phase,
p -> new LifecycleGroup(phase, this.timeoutPerShutdownPhase, lifecycleBeans, autoStartupOnly)
).add(beanName, bean);
}
});
if (!phases.isEmpty()) {
// 按分组启动bean
phases.values().forEach(LifecycleGroup::start);
}
}
生命周期bean的启动是一个递归方法,在启动时获取bean的所有依赖bean,在bean启动前先完成其依赖bean的启动,最后完成lifecycle bean的启动。
/**
* Start the specified bean as part of the given set of Lifecycle beans,
* making sure that any beans that it depends on are started first.
* @param lifecycleBeans a Map with bean name as key and Lifecycle instance as value
* @param beanName the name of the bean to start
*/
private void doStart(Map<String, ? extends Lifecycle> lifecycleBeans, String beanName, boolean autoStartupOnly) {
Lifecycle bean = lifecycleBeans.remove(beanName);
if (bean != null && bean != this) {
String[] dependenciesForBean = getBeanFactory().getDependenciesForBean(beanName);
for (String dependency : dependenciesForBean) {
// 递归调用完成lifecycle及其依赖bean的启动,确保其依赖bean先启动
doStart(lifecycleBeans, dependency, autoStartupOnly);
}
if (!bean.isRunning() &&
(!autoStartupOnly || !(bean instanceof SmartLifecycle) || ((SmartLifecycle) bean).isAutoStartup())) {
if (logger.isTraceEnabled()) {
logger.trace("Starting bean '" + beanName + "' of type [" + bean.getClass().getName() + "]");
}
try {
// 最后启动lifecycle bean
bean.start();
}
catch (Throwable ex) {
throw new ApplicationContextException("Failed to start bean '" + beanName + "'", ex);
}
if (logger.isDebugEnabled()) {
logger.debug("Successfully started bean '" + beanName + "'");
}
}
}
}
Api信息Documentation的数据准备 DocumentationPluginsBootstrapper#start()
也就是Swagger对应的生命周期bean的DocumentationPluginsBootstrapper#start()方法
@Override
public void start() {
if (initialized.compareAndSet(false, true)) {
log.info("Context refreshed");
// 获取Spring容器中所有的DocumentationPlugin插件bean,从这里可以看出来,swagger是支持多个DocumentationPlugin的
// 也就是支持多个Docket配置,Docket即是DocumentationPlugin的实现类
List<DocumentationPlugin> plugins = pluginOrdering()
.sortedCopy(documentationPluginsManager.documentationPlugins());
log.info("Found {} custom documentation plugin(s)", plugins.size());
for (DocumentationPlugin each : plugins) {
// 这一句感觉是应该放到else里的,毕竟只在else里用到
DocumentationType documentationType = each.getDocumentationType();
if (each.isEnabled()) {
// 这里buildContext()创建DocumentationContext
// scanDocumentation将DocumentationContext扫描到Documentation中并添加到DocumentationCache中
// 后续打开swagger静态页面调用 "/v2/api-docs"接口时,会从这个DocumentationCache中获取Documentation内容
scanDocumentation(buildContext(each));
} else {
log.info("Skipping initializing disabled plugin bean {} v{}",
documentationType.getName(), documentationType.getVersion());
}
}
}
}
创建DocumentationContextBuilder 将handlerProviders中的RequestHandler存入DocumentationContextBuilder
private DocumentationContextBuilder defaultContextBuilder(DocumentationPlugin plugin) {
DocumentationType documentationType = plugin.getDocumentationType();
// 从handlerProviders获取requestHandlers
List<RequestHandler> requestHandlers = from(handlerProviders)
.transformAndConcat(handlers())
.toList();
List<AlternateTypeRule> rules = from(nullToEmptyList(typeConventions))
.transformAndConcat(toRules())
.toList();
return documentationPluginsManager
.createContextBuilder(documentationType, defaultConfiguration)
.rules(rules)
.requestHandlers(combiner().combine(requestHandlers));
}
扫描DocumentationContext到Documentation:
public Documentation scan(DocumentationContext context) {
// 按@RestController分组的RequestMapping上下文
ApiListingReferenceScanResult result = apiListingReferenceScanner.scan(context);
ApiListingScanningContext listingContext = new ApiListingScanningContext(context,
result.getResourceGroupRequestMappings());
// Api接口,模型定义等上下文信息扫描
Multimap<String, ApiListing> apiListings = apiListingScanner.scan(listingContext);
Set<Tag> tags = toTags(apiListings);
tags.addAll(context.getTags());
// 将上下文中的信息填入DocumentationBuilder
DocumentationBuilder group = new DocumentationBuilder()
.name(context.getGroupName())
.apiListingsByResourceGroupName(apiListings)
.produces(context.getProduces())
.consumes(context.getConsumes())
.host(context.getHost())
.schemes(context.getProtocols())
.basePath(context.getPathProvider().getApplicationBasePath())
.extensions(context.getVendorExtentions())
.tags(tags);
Set<ApiListingReference> apiReferenceSet = newTreeSet(listingReferencePathComparator());
apiReferenceSet.addAll(apiListingReferences(apiListings, context));
ResourceListing resourceListing = new ResourceListingBuilder()
.apiVersion(context.getApiInfo().getVersion())
.apis(from(apiReferenceSet).toSortedList(context.getListingReferenceOrdering()))
.securitySchemes(context.getSecuritySchemes())
// Docket中配置的信息
.info(context.getApiInfo())
.build();
group.resourceListing(resourceListing);
return group.build();
}
到此Swagger的Documentation信息存入了缓存documentationCache中。
调用swagger接口,打开swagger的UI页面
打开swagger静态页面(http://localhost:8081/swagger-ui.html
)时,会调用swagger的/v2/api-docs
接口
@RequestMapping(
value = DEFAULT_URL,
method = RequestMethod.GET,
produces = { APPLICATION_JSON_VALUE, HAL_MEDIA_TYPE })
@PropertySourcedMapping(
value = "${springfox.documentation.swagger.v2.path}",
propertyKey = "springfox.documentation.swagger.v2.path")
@ResponseBody
public ResponseEntity<Json> getDocumentation(
// 分组名,用于区分不同Docket分组
@RequestParam(value = "group", required = false) String swaggerGroup,
HttpServletRequest servletRequest) {
String groupName = Optional.fromNullable(swaggerGroup).or(Docket.DEFAULT_GROUP_NAME);
// 根据分组名从documentationCache获取documentation对象
Documentation documentation = documentationCache.documentationByGroup(groupName);
if (documentation == null) {
LOGGER.warn("Unable to find specification for group {}", groupName);
return new ResponseEntity<Json>(HttpStatus.NOT_FOUND);
}
// 根据documentation对象生成swagger对象
Swagger swagger = mapper.mapDocumentation(documentation);
UriComponents uriComponents = componentsFrom(servletRequest, swagger.getBasePath());
swagger.basePath(Strings.isNullOrEmpty(uriComponents.getPath()) ? "/" : uriComponents.getPath());
if (isNullOrEmpty(swagger.getHost())) {
swagger.host(hostName(uriComponents));
}
return new ResponseEntity<Json>(jsonSerializer.toJson(swagger), HttpStatus.OK);
}
@Override
public Swagger mapDocumentation(Documentation from) {
if ( from == null ) {
return null;
}
Swagger swagger = new Swagger();
swagger.setVendorExtensions( vendorExtensionsMapper.mapExtensions( from.getVendorExtensions() ) );
swagger.setSchemes( mapSchemes( from.getSchemes() ) );
// 接口信息
swagger.setPaths( mapApiListings( from.getApiListings() ) );
swagger.setHost( from.getHost() );
// 模型定义
swagger.setDefinitions( modelMapper.modelsFromApiListings( from.getApiListings() ) );
swagger.setSecurityDefinitions( securityMapper.toSecuritySchemeDefinitions( from.getResourceListing() ) );
ApiInfo info = fromResourceListingInfo( from );
if ( info != null ) {
// ApiInfo
swagger.setInfo( mapApiInfo( info ) );
}
swagger.setBasePath( from.getBasePath() );
swagger.setTags( tagSetToTagList( from.getTags() ) );
List<String> list2 = from.getConsumes();
if ( list2 != null ) {
swagger.setConsumes( new ArrayList<String>( list2 ) );
}
else {
swagger.setConsumes( null );
}
List<String> list3 = from.getProduces();
if ( list3 != null ) {
swagger.setProduces( new ArrayList<String>( list3 ) );
}
else {
swagger.setProduces( null );
}
return swagger;
}
导出文档
导出adoc/md文档:
maven依赖
<!--单元测试依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--Swagger转换成标记语言的依赖-->
<dependency>
<groupId>io.github.swagger2markup</groupId>
<artifactId>swagger2markup</artifactId>
<version>1.3.3</version>
</dependency>
添加单元测试方法
@SpringBootTest
class BusinessApplicationTests {
@Test
void contextLoads() throws MalformedURLException {
// 设置标记语言为ASCIIDOC/MARKDOWN/txt中的一种
Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
.withMarkupLanguage(MarkupLanguage.ASCIIDOC).build();
// 设置JSon请求路径,及生成文件存放路径
// ?group=All参数可选,若Docket中未配置分组名,则此处不用加参数,否则需要添加要转换成文档的接口分组的分组名
Swagger2MarkupConverter.from(new URL("http://localhost:8081/v2/api-docs?group=All")).withConfig(config)
.build().toFile(Paths.get("src/docs/doc"));
}
}
使用maven插件将单元测试中生成的adoc/md文件转换成pdf文件
添加maven依赖
<dependency>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctorj-pdf</artifactId>
<version>2.1.6</version>
</dependency>
pom文件中添加如下插件
<plugin>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctor-maven-plugin</artifactId>
<version>1.5.3</version>
<dependencies>
<dependency>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctorj-pdf</artifactId>
<version>1.5.0-alpha.11</version>
</dependency>
<dependency>
<groupId>org.jruby</groupId>
<artifactId>jruby-complete</artifactId>
<version>9.1.8.0</version>
</dependency>
<dependency>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctorj</artifactId>
<version>1.5.4</version>
</dependency>
</dependencies>
<configuration >
<sourceDirectory>src/docs</sourceDirectory>
<sourceDocumentName>doc.adoc</sourceDocumentName>
</configuration>
<executions>
<execution>
<id>generate-pdf</id>
<phase>package</phase>
<goals>
<goal>process-asciidoc</goal>
</goals>
<configuration>
<backend>pdf</backend>
<outputDirectory>src/pdf</outputDirectory>
<doctype>book</doctype>
</configuration>
</execution>
</executions>
</plugin>
注意:插件中用到的几个依赖可能存在版本匹配问题,本文中使用的是一组可行组合,若需要使用最新版本依赖请自行摸索可行组合。