一、pom.xml依赖包
<!-- swagger-mvc --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.4.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.4.0</version> </dependency> <!-- json --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.6.5</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.6.5</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.6.5</version> </dependency>
springfox又要引用很多包,注意包冲突。
比如我遇到com.google.common.collect.Multimaps.asMap类找不到,但实际是有的,就因为之前引用的guava包版本冲突导致
二、在Spring mvc配置文件中声明SWAGGER配置bean
<bean class="springfox.documentation.swagger2.configuration.Swagger2DocumentationConfiguration" id="swagger2Config"/> <mvc:resources location="classpath:/META-INF/resources/" mapping="swagger-ui.html"/> <mvc:resources location="classpath:/META-INF/resources/webjars/" mapping="/webjars/**"/>
三、配置控制器
<context:component-scan base-package="com.api.controller" />
四、配置config
package com.santbbd.swagger; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; 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; @EnableWebMvc @EnableSwagger2 @ComponentScan(basePackages = {"ccom.api.controller"}) @Configuration public class RestApiConfig extends WebMvcConfigurationSupport{ @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.api.controller")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("。。。。。API") .termsOfServiceUrl("http://www.xxx.com") .contact(new Contact("xcc", "http://xxx.cn", "[email protected]")) .version("1.0") .build(); } }
五、添加文档注释
http://swagger.io/specification/
注解解释
六、访问http://127.0.0.1:8080/项目名/swagger-ui.html