Spring Boot程序员简书面面观

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

2019-01-21  本文已影响15人  我的小熊不见了

现在我们的项目中已经有了一个可供外部调用的rest api接口,随着项目的扩展以后会有越来越多的接口,这个时候就需要同时对外部提供关于接口的详细说明文档,而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>
@Configuration
@EnableSwagger2
/** 是否打开swagger **/
//@ConditionalOnExpression("'${swagger.enable}' == 'true'") 可以动态控制的开关,之后再使用
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

@Api(value = "注解在controller类上", description = "注解在controller类上")

@ApiOperation

@ApiOperation(value = "具体接口描述,写在controller的方法上, notes = "具体接口描述,写在controller的方法上")

@ApiModelProperty

@ApiModelProperty(value = "写在接口对应的实体类的属性上", example = "值")

@ApiParam

@ApiParam(value = "写在接口的入参上", required = true)

上一篇 下一篇

猜你喜欢

热点阅读