- 添加Swagger2依赖
<!-- swagger-mvc -->
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-core</artifactId>
<version>1.5.8</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml</groupId>
<artifactId>classmate</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.8.7</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.7</version>
</dependency>
<!-- swagger-mvc -->
- 创建Swagger2的配置类
@EnableWebMvc
@EnableSwagger2
/*@ComponentScan(basePackages = {"com.test"}) */
@Configuration
public class RestApiConfig extends WebMvcConfigurationSupport{
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.test"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Spring 中使用Swagger2构建RESTful APIs")
.termsOfServiceUrl("http://blog.csdn.net/he90227")
.contact("郭敬仰")
.version("1.0")
.build();
}
}
- 添加对swagger2静态资源的访问
<mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/"/>
<mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars
- 确保swagger2配置类被扫描到(假如RestApiConfig类在com.test目录下 )
<context:component-scan base-package="com.test" />
实际项目中注意事项:
(1)避免swagger2静态资源被拦截掉
(2)避免请求的链接被拦截
(3)哪个包需要支持swagger2必须指定
该demo的下载地址:https://gitee.com/jingyang3877/all-examples/blob/master/jingyang3877-swagger-test-demo-master.zip