Swagger2简介及入门案例

Swagger2

1 Swagger2概念

Swagger 是一款RESTFUL接口的、基于YAML、JSON语言的文档在线自动生成、代码自动生成的工具.

2 Swagger2入门案例

1 在springboot 项目工程pom.xml中添加依赖

   <!--swagger依赖-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

2 编写一个配置类

@Configuration//配置类
@EnableSwagger2//开启使用swagger
public class Swagger2Configuration {
    
    
   
    @Bean
    public Docket createRestApi() {
    
    
        return new Docket(DocumentationType.SWAGGER_2)
                .pathMapping("/")  //请求路径
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.zf"))//作用范围,在那个包下
                .paths(PathSelectors.any()) //指定包下所有请求
                .build().apiInfo(new ApiInfoBuilder()
                        .title("租房 ResutFul Api文档")//标题
                        .description("租房  ResutFul Api文档......") //描述
                        .version("v1.0") //版本
                        .build());
    }

}

3 在入口类之上加入注解

@ComponentScan(basePackages={
    
    "com.zf"})//扫描swagger配置
@EnableSwagger2

......

4 编写controller层

@RestController
@RequestMapping("/brand")
public class BrandController {
    
    

    @Autowired
    private BrandService brandService;
    //查询列表
    @GetMapping
    public Result<Brand> findAll(){
    
    
        //1.调用service
        List<Brand> brandList = brandService.findAll();
        if(brandList!=null ||brandList.size()>0){
    
    
            /**
             * 参数1表示状态,true或者false
             * 参数2表示调用状态码
             * 参数3表示信息
             * 参数4表示获取的数据
             */
            return new Result<Brand>(true, StatusCode.OK,"查询成功",brandList);
        }else{
    
    
            return new Result<Brand>(false, StatusCode.ERROR,"查询失败");
        }
    }
}

5 测试,访问 http://localhost:9011/swagger-ui.html#/
在这里插入图片描述
为了效果展示,我们可以对swagger接口进行汉化

1 在controller类中加入注解

1 标签专门用来标注类的 
	@Api(tags = "品牌管理接口api")
2 标注方法 
	@ApiOperation("查询列表接口")
3 对方法参数进行说明    
	@ApiImplicitParams({//参数集合
            @ApiImplicitParam(name = "id",value = "主键",defaultValue = "325415")
    })

2 测试 http://localhost:9011/swagger-ui.html#/
在这里插入图片描述
注意:
如果参数类型是map类型的接口则不太适合swagger插件,如果说使用swagger作为api工具的话,那么在写接口的时候尽量不要用map作为参数类型.
因为在swagger界面,不能明确描述出map中需要的参数.

猜你喜欢

转载自blog.csdn.net/ABestRookie/article/details/108460370
今日推荐