SpringBoot使用Swagger搭建Rest服务

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