SpringBoot 搭建 Rest 服務器,Swagger 提供 API 文檔支持。
Maven 添加 Swagger 支持:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.2.2</version>
</dependency>
Swagger 配置:
@Configuration
@EnableConfigurationProperties(SwaggerProperties.class)
@EnableSwagger2
public class SwaggerConfig {
@Autowired
private SwaggerProperties swaggerProperties;
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage(swaggerProperties.getBasePackage()))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfo(swaggerProperties.getTitle(),
swaggerProperties.getDescription(),
swaggerProperties.getVersion(),
swaggerProperties.getTermsOfServiceUrl(),
swaggerProperties.getContact(),
swaggerProperties.getLicense(),
swaggerProperties.getLicenseUrl());
}
}
建立 POJO:
@ApiModel("受權信息")
public class Auth {
@ApiModelProperty("用戶ID")
private Long id;
@ApiModelProperty("憑據")
private String ticket;
public Auth() {
}
public Auth(Long id, String ticket) {
this.id = id;
this.ticket = ticket;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTicket() {
return ticket;
}
public void setTicket(String ticket) {
this.ticket = ticket;
}
}
建立 Rest:
@Api(tags = "AUTH_AUTH", description = "受權-受權管理")
@RestController
@RequestMapping("/auths")
public class AuthController {
@Autowired
private AuthService authService;
@ApiOperation("獲取受權信息")
@RequestMapping(value = "/{userId}", method = RequestMethod.GET)
public Result<Auth> get(
@ApiParam(value = "用戶ID", required = true)
@PathVariable Long userId) {
return new Result<Auth>(authService.get(userId));
}
@ApiOperation("刪除受權信息")
@RequestMapping(value = "/{userId}", method = RequestMethod.DELETE)
public Result<Boolean> delete(
@ApiParam(value = "用戶ID", required = true)
@PathVariable Long userId) {
authService.delete(userId);
return new Result<Boolean>(true);
}
}
Swagger API 文檔如圖:
http://localhost:8888/api/swagger-ui.html
github代碼:https://github.com/AaronSheng/SpringBoot-Swaggerhtml