接口工具Swagger2

2020-07-15  本文已影响0人  Demon先生

SpringBoot配置Swagger2

添加依赖

pom.xml

<!-- Swagger2 Begin -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>
<!-- Swagger2 End -->

配置 Swagger2

注意:RequestHandlerSelectors.basePackage("com.demon.service")为 Controller 包路径,不然生成的文档扫描不到接

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;

@Configuration
public class Swagger2Configuration {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.demon.service"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Demon API 文档")
                .description("Demon API 网关接口")
                .version("1.0.0")
                .build();
    }
}

启用 Swagger2

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@SpringBootApplication
@EnableSwagger2
public class LoginApplication {

    public static void main(String[] args) {
        SpringApplication.run(LoginApplication.class,args);
    }
}

Swagger 常用注解说明

Swagger 通过注解表明该接口会生成文档,包括接口名、请求方法、参数、返回信息的等等。

访问 Swagger2

访问地址:http://ip:port/swagger-ui.html

image.png
上一篇下一篇

猜你喜欢

热点阅读