SpringBoot swagger使用向导
2020-02-25 本文已影响0人
孙宏志
在pom.xml文件中添加dependency
<!-- 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>
在 Application.properties 中启用swagger
spring.swagger2.enabled=true
添加SwaggerConfiguration类
@Configuration
@EnableSwagger2
public class SwaggerConfiguration {
@Value("${spring.swagger2.enabled}")
private Boolean swaggerEnabled;
public Docket createRestApi(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.enable(swaggerEnabled)
.select()
.apis(RequestHandlerSelectors.basePackage("top.willnew.tools.admin"))
.paths(PathSelectors.any()).build();
}
public ApiInfo apiInfo(){
return new ApiInfoBuilder()
.title("接口文档")
.description("api文档描述")
.termsOfServiceUrl("https://open.willnew.top")
.version("1.0")
.build();
}
}
在实体类中使用
@ApiModel("用户信息")
@Data
public class User {
@ApiModelProperty(value = "用户id")
private Integer id;
@ApiModelProperty(value = "用户名")
private String userName;
@ApiModelProperty(value = "密码")
private String password;
@ApiModelProperty(value = "性别 0-女,1-男")
private Byte sex;
@ApiModelProperty(value = "删除标记 默认0不删除,1删除")
private Byte deleted;
@ApiModelProperty(value = "记录创建时间")
private Date createTime;
@ApiModelProperty(value = "更新时间")
private Date updateTime;
}
在Controller中使用
@Api(description = "用户接口")
@RestController
@Slf4j
@RequestMapping("user")
public class UserController {
@Autowired
private UserMapper userMapper;
@ApiOperation("查询目前id的记录")
@GetMapping("/u/{id}")
public User findUserById(Long id){
User user = userMapper.selectById(id);
return user;
}
@ApiOperation("查询用户信息")
@PostMapping("all")
public List<User> queryAllUser(){
List<User> users = userMapper.selectList(null);
return users;
}
}