一、项目添加Swagger 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>二、项目主启动类 添加 Swagger2 注解
@EnableSwagger2 public class CustomerApplication { public static void main(String[] args) { SpringApplication.run(CustomerApplication.class, args); } }三、新建 Swagger2 配置类 与主启动类同级 结构如下图: 3.1 Swagger2 配置类 代码如下:
package com.customer; 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; @Configuration public class Swagger2 { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.customer.controller")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("springboot利用swagger构建api文档") .description("简单优雅的restfun风格") .termsOfServiceUrl("") .version("1.0") .build(); } }四、新建测试类 SwaggerTestController 测试代码如下:
package com.customer.controller; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController @Api(description = "Swagger测试类") public class SwaggerTestController { @ApiOperation(value = "getSwaggerTest-请求测试") @GetMapping(value = "getSwaggerTest") public String getSwaggerTest(@RequestParam("name") String name){ System.out.println("getSwaggerTest:" + name); return "getSwaggerTest:" + name; } }五、启动Eureka注册中心8900服务 和 此项目8902 服务, 访问Eureka注册中心 http://localhost:8900 如下所示: 结论:服务成功注册到Eureka注册中心。
5.1 浏览器开始访问 http://localhost:8902/swagger-ui.html 如下图: 开始进行Swagger 测试验证:
结论:Swagger进行测试和查看控制台输出分析-均有返回值信息(getSwaggerTest:测试)-验证成功。
5.2 此时此刻 SpringBoot项目整合Swagger2 就成功了。
