1.首先引入Swagger的依赖
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
2.编辑配置类
新建一个SwaggerConfig的配置类,赋值以下配置,这里的docket是单位,自己配置扫描的接口路径, 每个的GroupName必须不能相同.
正确配置后.访问项目地址加上/swagger-ui.html.我配置的效果如图所示.
package cn.ycms.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* Swagger2配置类
* 在与spring boot集成时,放在与Application.java同级的目录下。
* 或者通过 @Import 导入配置
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
/**
* 创建API应用
* apiInfo() 增加API相关信息
* 通过select()函数返回一个ApiSelectorBuilder实例,用来控制哪些接口暴露给Swagger来展现,
* 本例采用指定扫描的包路径来定义指定要建立API的目录。
* @return
*/
@Bean(value = "defaultGroup")
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.groupName("默认接口")
.enable(true)
.select()
.apis(RequestHandlerSelectors.basePackage("cn.ycms.controller.client"))
.paths(PathSelectors.any())
.build();
}
@Bean(value = "deliveryGroup")
public Docket createRestApi2() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.groupName("物流接口")
.enable(true)
.select()
.apis(RequestHandlerSelectors.basePackage("cn.ycms.controller.delivery"))
.paths(PathSelectors.any())
.build();
}
/**
* 创建该API的基本信息(这些基本信息会展现在文档页面中)
* 访问地址:http://项目实际地址/swagger-ui.html
* @return
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("ERP")
.description("EPR后端")
.termsOfServiceUrl("")
.contact("17815310629@163.com")
.version("1.0")
.build();
}
}
3.放行相关路径
如果你的项目有拦截器或者使用了相关的安全框架,请为下面的这些路径放行
.excludePathPatterns("/webjars/**")
.excludePathPatterns("/swagger-resources/**")
.excludePathPatterns("/v2/**")
.excludePathPatterns("/swagger-ui.html/**");
完