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

版权声明: https://blog.csdn.net/qq1311256696/article/details/86649675

现在我们的项目中已经有了一个可供外部调用的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'") 可以动态控制的开关,之后再使用
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)

您的关注是我最大的动力

猜你喜欢

转载自blog.csdn.net/qq1311256696/article/details/86649675