Springboot项目集成Swagger

参考 

Setting Up Swagger 2 with a Spring REST API

版本

Spring Boot:2.4.3

Swagger2:3.0.0

注意这里是SpringBoot项目,也要注意SpringBoot和Swagger2的版本,如果是不同版本,可能会报错!因为在SpringBoot2.4.3中用了springfox-swagger2而不是springfox-boot-starter,导致swagger-ui打不开,搞了一个下午!!!

引入依赖

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>3.0.0</version>
        </dependency>

配置Swagger2

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

@Configuration
public class SpringFoxConfig {                                    
    @Bean
    public Docket api() { 
        return new Docket(DocumentationType.SWAGGER_2)  
          .select()                                  
          .apis(RequestHandlerSelectors.any())              
          .paths(PathSelectors.any())                          
          .build();                                           
    }
}

测试

如果有Controller如下

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/student")
public class StudentController {

    @GetMapping("/list")
    public String findList() {
        return "this is find list method";
    }
}

启动项目,并且访问http://localhost:8080/swagger-ui/ 或者 http://localhost:8080/swagger-ui/index.html,就可以看到swagger页面

posted on 2021-03-16 21:18  dreamstar  阅读(194)  评论(0编辑  收藏  举报