这篇文章主要介绍如何在SpringBoot项目中集成Swagger。
导入pom依赖
pom.xml
<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.1</version>
</dependency>
编写配置类
SwaggerConfig
package com.zsky.swagger.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;
import java.util.ArrayList;
@Configuration
@EnableSwagger2 //开启Swagger2
public class SwaggerConfig {
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//RequestHandlerSelectors 配置要扫描接口的方式
//basePackage 指定要扫描的包
//any() 扫描全部
//none() 不扫描
.apis(RequestHandlerSelectors.basePackage("com.zsky.swagger.controller"))
//paths() 过滤,只扫描指定路径controller中 @RequestMapping("/zz/hello")
//.paths(PathSelectors.ant("/zz/hello"))
.build();
}
private ApiInfo apiInfo(){
final Contact DEFAULT_CONTACT = new Contact("zsky", "https://www.baidu.com", "55****713@qq.com");
return new ApiInfo(
"zsky-swagger",
"我希望每天叫醒我的不是闹钟,是梦想。",
"v1.0",
"https://fanyi.baidu.com/translate?aldtype=16047&query=xpected+1+arguments+but+found+0&keyfrom=baidu&smartresult=dict&lang=auto2zh#en/zh/term",
DEFAULT_CONTACT,
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList());
}
}
运行项目后在网址上输入 http://localhost:8080/swagger-ui.html 即可访问。