jeesite如何配置swagger_Spring Boot集成 Swagger,再也不写接口文档了!

f89784c2126eaf3b1ab445afad3c0046.png

Spring Boot 集成 Swagger

1、添加依赖

Maven依赖示例:

<!-- Swagger -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
</dependency>

2、在 Spring Boot 配置文件中添加配置参数。

swagger:
  title: API标题
  description: API描述
  version: 1.0
  terms-of-service-url: http://www.javastack.cn/
  base-package: cn.javastack.test.web
  contact:
    name: Javastack
    url: http://www.javastack.cn/
    email: admin@javastack.cn

3、添加配置类

@Getter
@Setter
@Configuration
@EnableSwagger2
@ConditionalOnClass(EnableSwagger2.class)
@ConfigurationProperties(prefix = "swagger")
public class SwaggerConfig {

    /**
     * API接口包路径
     */
    private String basePackage;

    /**
     * API页面标题
     */
    private String title;

    /**
     * API描述
     */
    private String description;

    /**
     * 服务条款地址
     */
    private String termsOfServiceUrl;

    /**
     * 版本号
     */
    private String version;

    /**
     * 联系人
     */
    private Contact contact;
    
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage(basePackage))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title(title)
                .description(description)
                .termsOfServiceUrl(termsOfServiceUrl)
                .version(version)
                .contact(contact)
                .build();
    }

}

如何使用

Swagger 默认会根据配置的包,扫描所有接口并生成对应的 API 描述和参数信息,但这样不是很直观,需要对每个接口和参数进行自定义描述。

常用的 Swagger 注解如下。

注解名称使用说明

使用示例如:

@Api(description = "登录模块")
@RestController
public class LoginController {
    
    @ApiOperation(value = "登录", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户名", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "password", value = "密码", dataType = "string", paramType = "query")})
    @PostMapping(value = "/login")
    public Object login(@RequestParam("username") String username, @RequestParam("password") String password) {
    
        // ...
          
    }
}
http://localhost:8080/swagger-ui.html

打开 swagger-ui 界面,可以看到所有的 API 接口定义,也可以在上面发起接口测试。

好了,今天的分享就到这里,更多 Spring Boot 文章正在撰写中,关注Java技术栈获取第一时间推送。

版权申明:本文系公众号 "Java技术栈" 原创,原创实属不易,转载、引用本文内容请注明出处,禁止抄袭、洗稿,请自重,尊重他人劳动成果和知识产权。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值