使用swagger发布API文档

swagger2可以方便的帮我们生成API文档并且在我们代码发生改变时自动改变文档信息

<!-- swaggerui相关依赖 -->

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.7.0</version>
</dependency>

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.7.0</version>
</dependency>

配置文件类

package com.caohao.bootlearn.config;

import io.swagger.annotations.SwaggerDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class Swagger2 {
    @Bean
    public Docket cerateRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.caohao.bootlearn"))//指定扫描controller的包
                .paths(PathSelectors.regex("/rest/.*"))//指定controller哪些请求的方法
                .build();
    }
    public ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("第一次使用swagger2创建API文档")
                .description("restful风格")
                .termsOfServiceUrl("http://www.caohao.com")
                .version("1.0")
                .build();
    }
}

常用注解
生成文档样式如下
生成的api文档打开链接http://localhost:8080/swagger-ui.html#/

原创文章 65 获赞 11 访问量 2063

猜你喜欢

转载自blog.csdn.net/qq_43147121/article/details/104268852