pom文件中引入依赖
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.1.6.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
创建Swagger2配置类
package com.springcloud.swagger2.configure;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
@Configuration
@EnableSwagger2 // 启用Swagger2
public class Swagger2 {
@Bean
public Docket createRestApi() {// 创建API基本信息
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.springcloud.swagger2"))// 扫描该包下的所有需要在Swagger中展示的API,@ApiIgnore注解标注的除外
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {// 创建API的基本信息,这些信息会在Swagger UI中进行显示
return new ApiInfoBuilder()
.title("Spring Boot中使用Swagger2构建RESTful APIs")// API 标题
.description("学习使用springboot集成swagger2")// API描述
.contact("liyf@qq.com")// 联系人
.version("1.0")// 版本号
.build();
}
}
Demo
package com.springcloud.swagger2.controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Slf4j
@Api(value = "springboot集成swagger demo",description = "swagger2控制层")
@RequestMapping(value="swagger2")
public class Swagger2Controller {
@ApiOperation(value = "swagger demo",notes = "实例")
@PostMapping(value="hello")
public void hello(@ApiParam(value = "用户名",name = "name",required = true) @RequestParam(value = "name",required = true) String name,
@ApiParam(value = "密码",name = "pwd",required = true) @RequestParam(value = "pwd",required = true) String pwd){
log.info(String.format("姓名[%s],密码[%s]",name,pwd));
}
}
访问swagger
http://localhost:8080/swagger-ui.html