您的位置:首页 > 编程语言 > Java开发

SpringBoot使用Swagger搭建Rest服务

2017-10-16 00:00 726 查看
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-Swagger
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息