swagger2在springboot中的使用

本文是为了记录在springboot项目中使用swagger2构建restful api文档,供使用人员查看,测试接口。
重点是使用流程。
前提:
对maven项目有一点了解
能构建一个最基础的helloworld springboot项目
1.在pom.xml文件中配置依赖包

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

2.创建swagger2的配置类
在HelloWorldController文件的同级位置创建swagger2的配置类文件,取名为swagger2Config,文件内容如下;
相关包自己导入

@Configuration
@EnableSwagger2
public class Swagger2Config {
    //访问路径 /swagger-ui.html
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.demo"))//根据自己项目修改
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        //访问地址 /swagger-ui.html
        return new ApiInfoBuilder()
                .title("RESTful APIs ")
                .description("Restful API文档")
                .version("1.0")
                .build();
    }
}

3.在HelloWorldController中添加注解
文件内容如下

@RestController
@Api(value = "用户服务信息查询",description = "HelloWorldController信息")
public class HelloWorldController {
    @RequestMapping("/api/hello")
    @ApiOperation(value = "sayHello信息查询")
    public String sayHello(){
        return "hello";
    }
}

4.启动项目,输入地址http://localhost:8080/swagger-ui.html查看结果
说明:这是一个简单的使用,是为了说明配置好swagger2Config文件之后,在controller里面使用注解就可以生成接口文档。如果想做添加更多的条件,修改更多的内容,就需要扩展这个代码。比如添加验证,扫描那些接口都可以在swagger2Config文件中配置,请查看相关文档。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值