Swagger的简单使用
Swagger官网:https://swagger.io/
使用Swagger
环境:
- SringBoot版本:2.5.6
- Swagger版本:2.9.2
新建一个SpringBoot项目,导入Swagger依赖
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<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.2</version>
</dependency>
创建Swagger配置类
import org.springframework.context.annotation.Configuration;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
}
启动项目,访问路径:http://localhost:8080/swagger-ui.html
Swagger配置
可以进行的配置在springfox.documentation.spring.web.plugins.Docket类中。
在SwaggerConfig配置类中进行配置
// 配置Swagger的Docket的Bean实例
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo());
}
// 配置Swagger信息
public ApiInfo apiInfo() {
// 作者信息
Contact contact = new Contact("hllog", "https://www.cnblogs.com/hllog/", "123456@qq.com");
return new ApiInfo("hllog的Swagger API文档",
"专注于技术",
"v1.0",
"https://www.cnblogs.com/hllog/",
contact,
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList<>());
}
使用Swagger生成文档
@ApiModel("用户")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
@ApiModelProperty("用户ID")
private Integer id;
@ApiModelProperty("用户名")
private String name;
@ApiModelProperty("密码")
private String password;
}
@RestController
public class HelloController {
@ApiOperation("简单的问候")
@GetMapping("/hello")
public String hello() {
return "Hello Swagger";
}
@ApiOperation("获取用户")
@PostMapping(value = "/user")
public User user() {
return new User();
}
@ApiOperation("对用户进行问候")
@GetMapping("/hello2")
public String hello2(@ApiParam("用户名") String name) {
return "Hello, " + name;
}
}
更多的Swagger注解参见io.swagger.annotations
包。