springboot整合swagger2

由于项目是前后端分离的,我们选择用 swagger 来暴露后台开发的接口,方便后端测试也方便前端调用

swagger 相比之前,使用起来要方便多了!下面小编就介绍一下 springboot 和 swagger2 的整合 

首先需要在 pom 里配置 swagger2

<!-- swagger2 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.0</version>
</dependency>
<!-- swagger-ui -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.0</version>
</dependency>

接下来需要配置 swagger2 的 configuration 类,这里只需要根据自己的结构,改下 basePackage 的值即可(表示添加 swagger 注解的类所在的包)

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class Swagger2 {

    protected ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Swagger2 APIs")
                .description("Swagger2 APIs")
                .version("1.0")
                .build();
    }

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("cn.byzt.controller"))
                .paths(PathSelectors.any())
                .build();
    }
}

然后就配置完成了,是不是很简单呢

小编贴上一小段测试代码

import cn.byzt.client.MyFtpClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/up")
@Api(tags = "测试")//类功能注释
public class FtpController {

    @Autowired
    private MyFtpClient client;

    @GetMapping("/d")
    @ApiOperation("测试方法")//方法功能注释
    //参数变量注释
    public String save(@ApiParam("测试变量") @RequestParam("a") String a) {
        client.test();
        return "lalala";
    }
}

附上运行结果

小编感觉 swagger2  目前最新版样式比之前好看,所以用的是目前最新版的 jar

小编还听说 swagger 2.8 版本有 bug,小编也测试了一下,的确出不来。。。。

具体问题就不深追究了,能用就行!!

 

posted @ 2018-10-25 10:57  chbyiming  阅读(166)  评论(0编辑  收藏  举报