1.引入依赖
<!-- Swagger依赖-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
<!-- Swagger end-->
2.SwaggerConfig 类
@Configuration注解该类,等价于XML中配置beans
通过@EnableSwagger2注解来启用Swagger2
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;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
/*通过creatRestApi()函数创建Docker的Bean之后,apiInfo()用来创建该Api的基本信息(这些基本信息会展现文档页面中)
*/
@Bean
public Docket creatRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//指定接口的位置,改为自己的controller位置
.apis(RequestHandlerSelectors.basePackage("com.xx.xx.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("自拟标题")
.description("接口文档描述")
.termsOfServiceUrl("")
.version("1.0")
.build();
}
}
3.启动项目,访问http://localhost:8080/swagger-ui.html