Swagger2与Spring三分钟即可上手集成

1. 介绍

 Swagger强大之处就在于他自动生成API文档,使后台开发不用频繁地写API文档。
 Swagger生成的api文档是实时更新的,你写的api接口有任何的改动都会在文档中及时的表现出来。
 看到这里是不是回想起之前手写的API文档那段日子,在现在看来确实很浪费时间。
 可以参考下swagger-springfox的[github地址](https://github.com/springfox/springfox)

2. maven依赖包

首先第一步引入swagger的依赖包,swagger2分为两个依赖包, 一个是core主要代码,一个是UI图形界面。springfox是swagger与java结合的框架

<!--swagger 在线api接口文档 start-->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>${swagger.version}</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>${swagger.version}</version>
</dependency>
<!--swagger end-->

3. 创建swagger的config类

创建配置swagger的config类。

/**
 * 项目名称:apidoc
 *
 * @description:
 * @author kris
 * @version V1.0.0
 *
 */
@Configuration
@EnableSwagger2
// Loads the spring beans required by the framework
public class MySwaggerConfig {

    @Autowired
    private TypeResolver typeResolver;
    @Bean
    public Docket petApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                //扫描@Api生成文档。方式:any, none, withClassAnnotation, withMethodAnnotation and basePackage
                .apis(RequestHandlerSelectors.basePackage("com.linyoga.controller"))
//                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
//                .apis(RequestHandlerSelectors.withClassAnnotation(ApiOperation.class))
                //扫描@Path生成文档。方式:regex, ant, any, none
                .paths(PathSelectors.any())
//                .paths(or(
//                        regex("/business.*"),
//                        regex("/some.*"),
//                        regex("/contacts.*"),
//                        regex("/pet.*"),
//                        regex("/springsRestController.*"),
//                        regex("/test.*")))
                .build()
                //swagger文档信息。在首页的左上角显示
                .apiInfo(new ApiInfo("swaggerTitle"
                        ,"my description"
                        ,"my version"
                        ,"my termsOfServiceUrl"
                        ,new Contact("my name"
                        ,"my url"
                        ,"my email")
                        ,"my license"
                        ,"my licenseUrl"
                        ,new ArrayList<VendorExtension>()
                        ))
                .pathMapping("/")
                //全局替换类型,LocalDate 替代为 String
//                .directModelSubstitute(LocalDate.class, String.class)
                .genericModelSubstitutes(ResponseEntity.class)
                .alternateTypeRules(
                        newRule(typeResolver.resolve(DeferredResult.class,
                                typeResolver.resolve(ResponseEntity.class, WildcardType.class)),
                                typeResolver.resolve(WildcardType.class)))
                //是否使用默认的响应信息
                .useDefaultResponseMessages(false)
                //覆盖指定RequsetMethod 全局响应信息 eg: 覆盖所有GET请求发生500响应信息
                .globalResponseMessage(RequestMethod.GET,
                        newArrayList(new ResponseMessageBuilder()
                                .code(500)
                                .message("500 message")
                                //响应model
                                .responseModel(new ModelRef("ErrorModel"))
                                .build()
                                ,new ResponseMessageBuilder()
                                .code(404)
                                .message("404 Not Found")
                                //Member是某个类的类名,需 .additionalModels(typeResolver.resolve(Member.class))
                                .responseModel(new ModelRef("Member"))
                                .build())
                                )
                //设置安全方案用于保护api。支持方案ApiKey,BasicAuth OAuth
                .securitySchemes(newArrayList(apiKey()))
                //设置安全上下文
                .securityContexts(newArrayList(securityContext()))
                //使用url模版
                .enableUrlTemplating(true)
                //全局操作参数
                .globalOperationParameters(
                        newArrayList(new ParameterBuilder()
                                .name("someGlobalParameter")
                                .description("Description of someGlobalParameter")
                                .modelRef(new ModelRef("string"))
                                .parameterType("query")
                                .required(true)
                                .build()))
                //为operation增加标签
                .tags(new Tag("Pet Service", "All apis relating to pets"))
                //添加自定义类为ModelRef
                .additionalModels(typeResolver.resolve(Member.class))
                .additionalModels(typeResolver.resolve(Order.class))
                ;
    }
    /**
     * apiKey 参数信息配置
     * @return
     */
    private ApiKey apiKey() {
        return new ApiKey("mykey", "api_key", "header");
    }

    /**
     * 安全上下文
     * @return
     */
    private SecurityContext securityContext() {
        return SecurityContext.builder()
                .securityReferences(defaultAuth())
//                .forPaths(PathSelectors.regex("/anyPath.*"))
                .forPaths(PathSelectors.any())
                .build();
    }

    /**
     * 默认的Auth
     * @return
     */
    List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope
                = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        return newArrayList(
                //在这里,我们使用上面定义好的相同的关键mykey中定义的安全方案
                new SecurityReference("mykey", authorizationScopes));
    }

    /**
     * 安全机制
     * @return
     */
    @Bean
    SecurityConfiguration security() {
        return SecurityConfigurationBuilder.builder()
                .clientId("test-app-client-id")
                .clientSecret("test-app-client-secret")
                .realm("test-app-realm")
                .appName("test-app")
                .scopeSeparator(",")
                .additionalQueryStringParams(null)
                .useBasicAuthenticationWithAccessCodeGrant(false)
                .build();
    }

    /**
     * UI配置
     * @return
     */
    @Bean
    UiConfiguration uiConfig() {
        return UiConfigurationBuilder.builder()
                .deepLinking(true)
                .displayOperationId(false)
                .defaultModelsExpandDepth(1)
                .defaultModelExpandDepth(1)
                .defaultModelRendering(ModelRendering.EXAMPLE)
                .displayRequestDuration(false)
                .docExpansion(DocExpansion.NONE)
                .filter(false)
                .maxDisplayedTags(null)
                .operationsSorter(OperationsSorter.ALPHA)
                .showExtensions(false)
                .tagsSorter(TagsSorter.ALPHA)
                .validatorUrl(null)
                .build();
    }

将该config注入到spring容器中,需要在spring.xml中配置bean

<bean class="com.xxx.swagger.SwaggerConfig" />

4.开发时注解

注解分别在controller接口和实体类pojo上。只展示在开发中最常用的注解,其余的可以在github上查找自己所需的注解。官方文档

**
 * @author 接口上的注解
 */
@Controller
@Api(value = "controller的名字描述")
@RequestMapping("/model")
public class BaseModelController extends BaseController {

    @Autowired
    private BaseModelService service;

    @RequestMapping("/test/{hhh}")
    @ApiOperation(notes = "接口路径", value = "test")
    @ApiImplicitParam(name = "参数名",value = "解释该参数的含义")
    public ResultObject test(@ApiParam(required = true, name="參數名") @PathVariable("hhh") String hhh ) {

        return resultObject;
    }

    @ApiOperation(value = "获取用户信息",httpMethod = "GET")
    @GetMapping(value = "getUserInfo/{id}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "param1", value = "参数名1", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "param2", value = "参数名1", required = true, paramType = "query", dataType = "String")
    })
    public User getUserInfo(@PathVariable @ApiParam(name = "id",value = "用户ID") Integer id,String param1,String param2){

        return new User();
    }
}
//如果需要在swagger-api文档展示该实体类的注释意思,则在实体类上加上@ApiModel
@ApiModel(value = "用户")
public class User {
    @ApiModelProperty(value = "ID")
    private Long id;
    @ApiModelProperty(value = "姓名")
    private String name;
    @ApiModelProperty(value = "手机号码")
    private String phone;
    ...getter/setter省略
}

5、Swagger-Ui的设置

直接引入ui的依赖包后,无需在导入静态文件。项目启动后,访问http://你的地址/swagger-ui.html#/

若有疑问,请在下方留言提问。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值