网上各种博客都有关于swagger2集成到springmvc.springboot框架的说明,但作者在整合到geoserver中确碰到了问题,调试一番最后才解决,遂总结一下。
swagger2集成只需要简单三步:
1、配置swagger2依赖库;
2、创建SwaggerConfig配置类,用于创建api文档;
3、配置swagger页面的资源映射,swagger的页面资源都在springfox-swagger-ui.jar包里;
这些步骤可在新建工程中实现,也可直接修改已有工程(作者是在gs-restconfig工程中修改的)
具体效果如下:
依赖库(pom.xml):
<!-- add for rest api doc by lxh --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.7</version> </dependency>
配置类(新建包和类):
1 package org.geoserver.rest.swagger; 2 3 import org.springframework.context.annotation.Bean; 4 import org.springframework.context.annotation.Configuration; 5 import org.springframework.web.servlet.config.annotation.EnableWebMvc; 6 import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; 7 import springfox.documentation.builders.ApiInfoBuilder; 8 import springfox.documentation.builders.RequestHandlerSelectors; 9 import springfox.documentation.service.ApiInfo; 10 import springfox.documentation.spi.DocumentationType; 11 import springfox.documentation.spring.web.plugins.Docket; 12 import springfox.documentation.swagger2.annotations.EnableSwagger2; 13 14 @Configuration 15 @EnableWebMvc 16 @EnableSwagger2 17 public class SwaggerConfig { 18 19 @Bean 20 public Docket api() { 21 Docket dock = new Docket(DocumentationType.SWAGGER_2) 22 .select() 23 .apis(RequestHandlerSelectors.basePackage("org.geoserver.rest.catalog")) 24 .build() 25 .apiInfo(apiInfo()) 26 .ignoredParameterTypes(org.geotools.styling.Stroke.class, 27 freemarker.template.Template.class, 28 org.geotools.ows.wms.Layer.class, 29 org.geotools.ows.wmts.model.WMTSLayer.class); 30 return dock; 31 } 32 33 private ApiInfo apiInfo() { 34 return new ApiInfoBuilder() 35 .title("Hgisserver Rest API docs") 36 .description("RESTful API description") 37 .version("3.6.4") 38 .build(); 39 } 40 }
资源映射(applicationContext.xml中增加):
<!-- add by lxh for swagger doc --> <mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/" /> <mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/" />
只修改这些启动geoserver,可以访问http://localhost:8080/geoserver/swagger-ui.html,但是会报错:http://localhost:8080/geoserver/v2/api-docs Not Found,控制台也会输出:
里面关于model属性的问题,通过添加ignoredParameterTypes可避免警告,至于/v2/api-docs找不到的原因则是geoserver配置的Advanced Dispatch Filter(org.geoserver.platform.AdvancedDispatchFilter)将其过滤掉了。
这个问题查找了两天(!!),最终修改AdvancedDispatchFilter类的过滤源码,最后结果如下:
终于正常启动了,贴张图: