SpringBoot集成Swagger

swagger _ helloworld

1.导包

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

2.配置Swagger 基本配置

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

import javax.print.Doc;
import java.util.ArrayList;

@Configuration
@EnableSwagger2 //开启swagger2
public class SwaggerConfig {

    //配置了swagger的bean实例
    @Bean
    public Docket docket() {
        return new Docket(DocumentationType.SWAGGER_2)
        //设置接口信息
        .apiInfo(apiInfo())
        //配置分组
        .groupName("一阵雄风")
        //是否启用swagger
        .enable(flag)
        .select()
    	.apis(RequestHandlerSelectors.basePackage("top.yc9064.swagger.controller"))
    	//过滤  那个路径
        //.paths(PathSelectors.ant("/user/**"))  只扫描请求前面带了 /user/ 的 注解 的 接口
		.build();;
    }


    private ApiInfo apiInfo() {
        //作者信息
        Contact contact = new Contact("张三", "https://yc9064.gitee.io/", "906478612@qq.com");
        return new ApiInfo(
                "张三的swaggerApi文档",
                "加油",
                "V1.0",
                "https://www.baidu.com",
                contact,
                "Apacher 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0",
                new ArrayList<>()
        );
    }
}

controller

@RestController
public class Hellocontroller {


    @ApiOperation(" 接口的注释:这个接口会返回' hello swagger!' ")//默认为接口的方法名称  
    @GetMapping("/hello")
    public String hello(){
        return "Hello swagger!";
    }

    //只要返回值存在实体类  就会出现在model
    @PostMapping("/user")
    public User getUser(){
        return new User();
    }
}


3.启动Springbootapplication访问swagger

http://localhost/swagger-ui.html
在这里插入图片描述

实体配置

  1. 新建一个用户实体类
  2. 添加 ApiModel注解
    在这里插入图片描述
    信息将写入swagger
    在这里插入图片描述
    总结:
    只要接口返回的是实体类, 信息就会出现在Model下, 而ApiModel 可以为 其添加注释信息

测试

可以在swagger中测试post请求
在这里插入图片描述
在swagger中的文档执行测试
在这里插入图片描述

总结

  1. 可以给难理解的接口加注释 (在参数,方法名和接口上)
  2. 接口文档实时更新
  3. 可以在线测试Post请求
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值