一、快速实现
1.1、导入 Maven 依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
1.2、直接在 SpringBoot 启动类上添加 @EnableOpenApi 注解
@SpringBootApplication
@EnableOpenApi
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
1.3、启动项目,尝试访问:"/swagger-ui/" 或 “/swagger-ui/index.html”
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/136b4809942b6874d202c26063a48665.png#pic_center)
二、深入了解 Swagger,并简单实现
2.1、创建一个 Swagger 的 JavaConfig 类,进行简单配置
@Configuration
public class SwaggerConfig {
@Bean
public Docket docket(Environment environment) {
Profiles profiles = Profiles.of("dev");
boolean flag = environment.acceptsProfiles(profiles);
return new Docket(DocumentationType.OAS_30)
.apiInfo(apiInfo())
.enable(flag)
.groupName("root")
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.controller"))
.paths(PathSelectors.ant("/**"))
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("Swagger3 初步配置").version("1.0").build();
}
}
2.2、创建实体类,并给实体类添加注释
@ApiModel("用户实体类")
public class User {
@ApiModelProperty("唯一标识")
private String uuid;
@ApiModelProperty("用户账号")
private String username;
@ApiModelProperty("用户密码")
private String password;
}
2.3、创建接口层(Controller),添加注释
@Api(tags = "路由跳转")
@RestController
public class IndexController {
@GetMapping({"/", "/index", "/index.html"})
public String index() {
return "Hello swagger!";
}
@PostMapping("/user")
public User user() {
return new User();
}
@ApiOperation("Get 测试")
@GetMapping("/user/get")
public User user(@ApiParam("用户账号") String username, @ApiParam("用户密码") String password) {
return new User(username,password);
}
@ApiOperation("Post 测试")
@GetMapping("/user/post")
public User user(@ApiParam("用户实体类") User user) {
return user;
}
}
2.2、重启项目,在此访问 Swagger 的路径:"/swagger-ui/" 或 “/swagger-ui/index.html”
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/8923bd7e375896f76e1b0b2f7b89d87d.png#pic_center)