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

SpringBoot使用Jersey+Swagger搭建Rest服务

2017-10-16 00:00 931 查看
SpringBoot 使用 Jersey 搭建 Rest 服务器,Swagger 提供 API 文档支持,为什么不直接用 SpringBoot 自带的 Rest 接口呢?因为 SpringBoot 自带的接口,Swagger 不能扫描其接口,只能扫描其实现。

Maven 添加 Jersey 和 Swagger 支持:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jersey</artifactId>
</dependency>

<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-jersey2-jaxrs</artifactId>
<version>1.5.12</version>
</dependency>

<!-- swagger 静态资源 -->
<dependency>
<groupId>org.webjars</groupId>
<artifactId>swagger-ui</artifactId>
<version>2.2.10</version>
</dependency>
<dependency>
<groupId>org.glassfish.hk2</groupId>
<artifactId>spring-bridge</artifactId>
<version>2.5.0-b34</version>
</dependency>

配置 Jersey 和 Swagger:
@Component
@EnableConfigurationProperties(SwaggerProperties.class)
public class JerseySwaggerConfig extends JerseyConfig {
@Autowired
private SwaggerProperties swaggerProperties;

@PostConstruct
private void init() {
configSwagger();
register(SwaggerSerializers.class);
register(ApiListingResource.class);
}

private void configSwagger() {
BeanConfig beanConfig = new BeanConfig();
beanConfig.setTitle(swaggerProperties.getTitle());
beanConfig.setVersion(swaggerProperties.getVersion());
beanConfig.setContact(swaggerProperties.getContact());
beanConfig.setBasePath(swaggerProperties.getBasePath());
beanConfig.setResourcePackage(swaggerProperties.getResourcePackege());
beanConfig.setScan(true);
}
}

创建 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;
}
}

创建 API:
@Api(tags = "AUTH_AUTH", description = "授权-授权管理")
@Path("/auths")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public interface AuthResource {
@ApiOperation("获取授权信息")
@Path("/{userId}")
@GET
public Result<Auth> get(
@ApiParam(value = "用户ID", required = true)
@PathParam("userId") Long userId);

@ApiOperation("删除授权信息")
@Path("/{userId}")
@DELETE
public Result<Boolean> delete(
@ApiParam(value = "用户ID", required = true)
@PathParam("userId") Long userId);
}

创建 API 实现
@RestResource
public class AuthResourceImpl implements AuthResource {
@Autowired
private AuthService authService;

@Override
public Result<Auth> get(Long userId) {
return new Result<Auth>(authService.get(userId));
}

@Override
public Result<Boolean> delete(Long userId) {
throw new NotFoundException("未找到的资源");
}
}

Chrome 安装 Swagger 插件,Swagger API 文档如图:
http://localhost:8888/api/swagger.json



github代码:https://github.com/AaronSheng/SpringBoot-Jersey
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息