欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springboot使用swagger构建api文档

程序员文章站 2022-07-02 21:10:49
...

本篇文章是快速的入门配置
依旧是简单粗暴的几个配置,实现API的管理和接口访问

  1. 引入依赖
	  <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>

2、启动类上开启注解

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

@EnableSwagger2
@SpringBootApplication
public class DemoApplication {
   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
   }
}

3、添加swagger的相关配置

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 SwaggerConfig {

   @Bean
   public Docket createRestApi() {
      return new Docket(DocumentationType.SWAGGER_2)
         .apiInfo(apiInfo())
         .select()
         .apis(RequestHandlerSelectors.basePackage("这里配置controller所在包的路径。如cn.controller"))
         .paths(PathSelectors.any())
         .build();
   }

   private ApiInfo apiInfo() {
      return new ApiInfoBuilder()
         .title("springboot利用swagger构建api文档")
         .description("简单优雅的restfun风格")
         //                .termsOfServiceUrl("http:/xxx/xxx")
         .contact("test")
         .version("1.0")
         .build();
   }

}

4、好了,准备测试用的controller

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Api(value = "测试api接口", tags = "简单的样例")
public class TestController {

   @GetMapping("/test")
   @ApiOperation(value = "简单的样例,演示效果用")
   public String exportSimulationLicense(@RequestParam String param) throws Exception{
      return param;
   }

}

查看效果
访问 http://localhost:8001/swagger-ui.html。注意这里的8001端口是服务启动的端口,需要根据自身情况修改
springboot使用swagger构建api文档

相关标签: springboot