springboot集成swagger主要通过以下3步:
1、添加依赖
2、增加配置类
3、在接口中使用
总的来说还是挺方便的,下面具体介绍下。
1、添加依赖,在pom文件里添加以下依赖,可以配置公共模块的pom文件里:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
2、在工程中增加一个配置类:
package com.xdk.common.config.outter;
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 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("使用Swagger构建RESTful Apis")
.description("my apis")
.termsOfServiceUrl("www.baidu.com")
.version("1.0")
.build();
}
}
3、接下来就是如何在controller中使用了,这里不仔细介绍,只是流程性的简单给出个例子:
@Api(tags = "TestController", description = "测试swagger")
@RestController
@RequestMapping("/test")
public class TestControllor {
@ApiOperation("打招呼")
@GetMapping("/say/hello")
public String sayHello(@RequestParam("arg") String arg) {
return "Hello " + arg ;
}
}
最后说明下,如果使用的SpringCloud框架,可在配置文件中配置:
使得通过点击eureka前端的注册列表界面的实例,就可以直接跳转到该实例对应的swagger界面。