SpringBoot引入Swagger生成API文档
2022-01-03 本文已影响0人
Rick97
- SpringBoot版本:2.5.6
- Swagger版本:SpringFox 3.0.0
p.s. SpringBoot2.6.2版本不支持SpringFox 3.0.0
1.引入依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
2.启动类增加注解@EnableOpenApi
package com.rickslab.learnprog;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.oas.annotations.EnableOpenApi;
@MapperScan("com.rickslab.learnprog.domain.mapper")
@EnableOpenApi
@SpringBootApplication
public class LearnProgApplication {
public static void main(String[] args) {
SpringApplication.run(LearnProgApplication.class, args);
}
}
3.接口增加相关注解
- @Api(tags="xxx"):接口说明,放在类声明前面
- @ApiOperation("xxx"):方法说明,
- @ApiIngore:隐藏该方法
package com.rickslab.learnprog.web;
import com.rickslab.learnprog.domain.mapper.UserMapper;
import com.rickslab.learnprog.domain.po.UserPo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import javax.servlet.http.HttpServletRequest;
@Api(tags = "用户管理")
@RestController
@RequestMapping("/user")
public class UserController {
private final UserMapper userMapper;
@Autowired
UserController(UserMapper userMapper) {
this.userMapper = userMapper;
}
@ApiOperation("根据用户名查找用户")
@PostMapping("/findByName")
public UserPo findByName(HttpServletRequest request) {
String name = request.getParameter("name");
return userMapper.findByName(name);
}
@ApiIgnore
@PostMapping("/insert")
public int insert(String name, Integer age) {
return userMapper.insert(name, age);
}
}
4.实体类增加相关注解
- @ApiModel("xxx"):实体类说明
- @ApiModelProperty("xxx"):实体类属性说明
package com.rickslab.learnprog.domain.po;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
@ApiModel("用户信息实体")
public class UserPo {
@ApiModelProperty("姓名")
private String name;
@ApiModelProperty("id")
private Long id;
@ApiModelProperty("年龄")
private Integer age;
}
5.访问
启动应用!访问swagger页面:http://localhost:8080/swagger-ui/index.html