Spring Boot从入门到精通-集成swagger

时间:2022-06-21
本文章向大家介绍Spring Boot从入门到精通-集成swagger,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

现在我们的项目中已经有了一个可供外部调用的rest api接口,随着项目的扩展以后会有越来越多的接口,这个时候就需要同时对外部提供关于接口的详细说明文档,而swagger帮我们使用很少的时间就可以构建出一套接口文档。

  • 首先在pom.xml中引用swagger所需的依赖。
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <scope>compile</scope>
 </dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
 </dependency>
  • 然后在代码中开启swagger
@Configuration
@EnableSwagger2
/** 是否打开swagger **/
//@ConditionalOnExpression("'${swagger.enable}' == 'true'") 可以动态控制的开关,在生产环境关闭swagger
public class SwaggerConfig {
    
    
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                 // 扫描controller路径
                .apis(RequestHandlerSelectors.basePackage("com.demo.controller"))
                .paths(PathSelectors.any())
                .build();
    }
    
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("springt boot 从入门到精通 api")
                .description("springt boot 从入门到精通 api")
                .termsOfServiceUrl("https://www.jianshu.com/u/c9deb1bda6ce")
                .contact("https://www.jianshu.com/u/c9deb1bda6ce")
                .version("1.0.0")
                .build();
    }
    
}

这一步完成之后,启动项目,打开 localhost:8080/swagger-ui.html#/就可以看到swagger的界面了,并且我们写好的那个接口也已经躺在那里等我们的调用。 swagger还有更多的注解帮助我们完善接口文档。

swagger注解

从源码中可以看到swagger提供了这么多注解,下面我们将常用的几个进行讲解:

@Api:注解在controller上,可以有以下参数
    // 接口描述
    String value() value"";
    // 会在swagger页面显示两个标签
    String[] tags() default {""};
    // 是否隐藏
    boolean hidden() default false;
@ApiOperation:注解在接口的方法上
     // 接口描述
    String value();
     // 会在接口上显示笔记
    String notes() default "";

    String[] tags() default {""};
    // 是否隐藏
    boolean hidden() default false;
@ApiParam:注解在接口参数上
    // 描述
    String value() default "";
    // 默认值
    String defaultValue() default "";
    // 是否必填
     boolean required() default false;
    // 是否隐藏
    boolean hidden() default false;
    // 示例值
    String example() default "";
@ApiModelProperty:注解在model上
    // 描述
     String value() default "";
    // 笔记
    String notes() default "";
    // 是否隐藏
    boolean hidden() default false;
    // 示例参数
    String example() default "";
    //允许空置
    boolean allowEmptyValue() default false;