Springboot整合swagger指南

Springboot整合swagger指南

1. 安装使用

1.1 下载依赖
<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>

不同版本,配置有所差异,最好采用相同版本

1.2 编写swagger配置文件
@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket docket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(myApiInfo());
    }

    private ApiInfo myApiInfo() {
        Contact DEFAULT_CONTACT = new Contact("夏2同学", "http://appletest.cn", "1754082565@qq.com");

        return new ApiInfo(
               "Api Documentation",
               "Api Documentation description...",
               "1.0",
               "urn:tos",
                DEFAULT_CONTACT,
                "Apache 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0",
                new ArrayList()
        );
    }


}
1.3 启动使用

对,springboot集成swagger,就是这么简单!

启动后,就可以看到我们的swagger界面。

image-20210708160247068

它默认会扫描,我们项目下面的所有controller和bean层,帮助我们直接生成文档。

controller部分代码如下:

@RestController
@Api(description = "hello工程")
public class HelloController {

    @GetMapping("/hello")
    @ApiOperation("hello的Api")
    public String hello(@ApiParam("用户名") String username){
        return "hello " + username;
    }

    @PostMapping("/post")
    public String post(String username, @RequestParam String password){
        return "hello " + username + ", " + password;
    }

}

2. 注解使用

通过使用注解,可以让swagger上显示的信息更加语义化,减少沟通的成本。

2.1 用于注解pojo的两个:
@ApiModel(description = Content类描述)
public class Content {
@ApiModelProperty(标题)
private String title;

实例:

@Data
@AllArgsConstructor
@NoArgsConstructor
@ApiModel("user实体类")
public class User {
    @ApiModelProperty("用户名")
    private String username;
    @ApiModelProperty("密码")
    private String password;
    @ApiModelProperty("生日")
    private Date birthDate;
}

swagger运行效果:

image-20210708161209196

2.2 用于控制器类的3个
@Api(tags = {Index控制器}) // tags是对Controller的接口重新分类
@Controller
public class IndexController {
    @ApiOperation(getContent方法)
    @GetMapping("/test")
    @ResponseBody
    public Content getContent(@ApiParam(名字) @RequestParam String name) {
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

夏2同学

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值