SpringBoot框架 之 Swagger2

目录

集成Swagger2

Swagger2简介

1.随项目自动生成强大RESTful API文档,减少工作量
2.API文档与代码整合在一起,便于同步更新API说明
3.页面测试功能来调试每个RESTful API

1.添加依赖

<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>

2.创建Swagger2配置类

@Configuration
@EnableSwagger2
public class SwaggerConfig {
        @Bean
        public Docket createRestApi() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .apiInfo(apiInfo())
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("com.itlike"))// 指定扫描包下面的注解
                    .paths(PathSelectors.any())
                    .build();
        }
        // 创建api的基本信息
        private ApiInfo apiInfo() {
            return new ApiInfoBuilder()
                    .title("集成Swagger2构建RESTful APIs")
                    .description("集成Swagger2构建RESTful APIs")
                    .termsOfServiceUrl("https://www.baidu.com")
                    .contact("itlike")
                    .version("1.0.0")
                    .build();
        }
}

3.在控制器方法上添加对应api信息

@RequestMapping("hero")
public class MyController{
    @Autowired
    private HeroService heroService;
    
    @ApiOperation(value="获取英雄信息",notes="根据id来获取英雄详细信息)
    @ApiImplicitParam(name="id",value="用户ID",required=true,dataType="String")
    @RequestMapping("{id}")
    ResponseBody
    public Hero getHero(@PathVariable("id")Long id,ModelMap modelMap){
        Hero hero=heroService.getHeroById(id);
        modelMap.addAttribute("hero",hero);
        return hero;
    }
}

4.启动Spring boot,访问Swagger UI界面

http://localhost/swagger-ui.html#/

常见Api

@Api(value="用户controller",tags={"用户操作接口"})
    Api 用在类上,说明该类的作用。可以标记一个Controller类做为swagger 文档资源
    
@ApiOperation(value="获取用户信息",notes="注意问题点",httpMethod="GET")
    用在方法上,说明方法的作用,每一个url资源的定义,使用方式
    
@ApiImplicitParams({@ApiImplicitParam(name="id",value="用户id",dataType="Long", paramType = "path")})
    参数说明
    
@ApiIgnore()
    忽略方法
上一篇:springboot 2 整合swagger2


下一篇:.net mvc 分页