SpringBoot集成Swagger2与Swagger3.0的不同

Swagger2:

pom依赖:

        <!--swagger依赖-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.8.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.8.0</version>
        </dependency>

配置类(SwaggerConfig):

@Configuration //声明该类为配置类
@EnableSwagger2//声明启动Swagger2
public class SwaggerConfig {
    @Bean
    public Docket customDocket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis("com.stars.springbootswagger.controller")//扫描的包路径
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("API接口文档")//文档说明
                .version("1.0.0")//文档版本说明
                .build();
    }
}

需要注意的是Swagger2需要实现WebMvcConfigurer对静态资源进行处理

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
    /**
     * 静态资源映射
     * @param registry
     */
    public void addResourceHandlers(ResourceHandlerRegistry registry){

        //解决swagger访问404
        registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
       
    }
}

SpringBoot项目启动后浏览器访问:http://localhost:9902/swagger-ui.html(此端口为项目启动配置的端口)

Swagger3:

pom依赖:

        <!--swagger依赖-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>

这里和Swagger2的依赖不一样。

配置类(SwaggerConfig):

@Configuration //声明该类为配置类
@EnableOpenApi //声明启动Swagger
public class SwaggerConfig {
    @Bean
    public Docket customDocket() {
        return new Docket(DocumentationType.OAS_30)
                .pathMapping("/")
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))//扫描类上有@Api注解的
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("API接口文档")//文档说明
                .version("1.0.0")//文档版本说明
                .build();
    }
}

这里的配置类的注解也稍有不同。Swagger3是不需要对静态资源进行处理的,内部已经做过了处理,可以看一下Swagger3的源码(SwaggerUiWebMvcConfigurer.java

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package springfox.boot.starter.autoconfigure;

import org.springframework.util.StringUtils;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

public class SwaggerUiWebMvcConfigurer implements WebMvcConfigurer {
    private final String baseUrl;

    public SwaggerUiWebMvcConfigurer(String baseUrl) {
        this.baseUrl = baseUrl;
    }

    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String baseUrl = StringUtils.trimTrailingCharacter(this.baseUrl, '/');
        registry.addResourceHandler(new String[]{baseUrl + "/swagger-ui/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/springfox-swagger-ui/"}).resourceChain(false);
    }

    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController(this.baseUrl + "/swagger-ui/").setViewName("forward:" + this.baseUrl + "/swagger-ui/index.html");
    }
}

SpringBoot项目启动后浏览器访问:http://localhost:9902/swagger-ui/index.html(此端口为项目启动配置的端口)

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 要在Spring Boot项目中集成Swagger 3.0,您需要以下步骤: 1. 在pom.xml文件中添加Swagger的依赖 2. 在启动类中添加@EnableSwagger2注解 3. 创建一个Docket Bean,并配置Swagger信息 4. 在控制器类和API方法上添加Swagger注解,来生成API文档 5. 启动项目并访问http://localhost:端口/swagger-ui.html查看API文档 具体的实现方法可以参考Swagger的官方文档和示例代码。 ### 回答2: Swagger是一款流行的API文档工具,Swagger 3.0 是当前最新版本,提供了全新的设计风格和功能。Spring Boot 是一款非常优秀且流行的Java框架,能够轻松集成和搭建不同的应用。在构建RESTful web服务时,我们可能需要使用Swagger来进行API的文档化和测试。由于Spring Boot的优秀特性和灵活性,它可以很方便地与Swagger进行集成Spring BootSwagger集成,主要依赖于两个库,它们分别是Swagger UI和Swagger Core。Swagger UI库是提供了一个交互式的Web页面,可以让我们很方便地查看和测试API。Swagger Core库则是提供了注解和解析功能,可以实现和扫描类、方法和参数的注解,最后生成API文档。 那么接下来,我将简单介绍在Spring Boot中如何集成Swagger 3.0,并说明如何使用它来生成我们需要的API文档。 首先,在你的Spring Boot项目中引入Swagger UI和Swagger Core的依赖库,建议使用最新版本,这样可以获得更好的性能和支持: ```xml <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0-SNAPSHOT</version> </dependency> ``` 然后,在入口类(通常是Applicaton类)上添加注解@EnableSwagger2。例如: ```java @SpringBootApplication @EnableSwagger2 public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } } ``` 接下来,我们需要配置Swagger的基础信息,例如API文档的标题、描述和版本号等。在Spring Boot中,可以在application.yml或者application.properties配置文件中添加以下内容: ```yaml springfox.documentation.swagger-ui.enabled=true springfox.documentation.swagger-ui.title=My Awesome API Doc springfox.documentation.swagger-ui.description=Description for My Awesome API Doc springfox.documentation.swagger-ui.version=1.0 springfox.documentation.swagger-ui.terms-of-service-url=http://www.mycompany.com/terms springfox.documentation.swagger-ui.contact.name=API Support springfox.documentation.swagger-ui.contact.url=http://www.mycompany.com/support springfox.documentation.swagger[email protected] springfox.documentation.swagger-ui.license.name=Apache 2.0 springfox.documentation.swagger-ui.license.url=http://www.apache.org/licenses/LICENSE-2.0.html ``` 之后,我们需要在Controller层的类或者方法上加上Swagger的注解来描述API。例如: ```java @RestController public class MyController { @ApiOperation(value = "Get username", notes = "Return username by user id") @ApiResponses(value = { @ApiResponse(code = 200, message = "OK", response = String.class), @ApiResponse(code = 500, message = "Internal server error") }) @GetMapping("/users/{id}") public String getUser(@PathVariable(name = "id") Long id) { return "user-" + id; } } ``` 以上示例中,用到的注解包括:@ApiOperation,用来定义操作方法的描述信息;@ApiResponses,用来定义操作方法的返回结果;@GetMapping,用来定义Controller类的Get请求。 最后,我们需要访问Swagger UI的页面,在浏览器地址栏输入http://localhost:8080/swagger-ui/index.html,即可查看到API文档的Web界面。在UI界面上,我们可以看到API的基本信息、请求参数、响应结果等内容。同时,在UI界面上,也可以直接对API进行测试并调试。特别是,在操作全局变量或者数据库的情况下,使用Swagger可帮助我们大大提高开发效率和减少错误。 ### 回答3: Swagger是一个开源的API框架,可以生成API文档和测试客户端,并提供了可视化的UI让用户直接测试API。而Spring Boot是一个非常流行的Java框架,它简化了Java web应用的开发。针对这两个框架的结合,可以实现在Spring Boot集成Swagger,从而给Java web应用带来更加便捷的API文档和测试方式。本文详细介绍了如何在Spring Boot集成Swagger3.0。 1、引入Swagger3.0依赖 首先,我们需要在pom.xml文件中引入Swagger3.0的依赖包: ```xml <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency> ``` 2、配置Swagger3.0Spring Boot的配置文件application.yml中,我们需要添加Swagger3.0的配置信息。具体而言,需要添加以下内容: ```yaml springfox: documentation: swagger-ui: enabled: true # 是否启用Swagger UI springfox: documentation: enabled: true # 是否启用Swagger文档 swagger-ui: enabled: true # 是否启用Swagger UI title: API文档 # Swagger UI的标题 description: API接口文档 # Swagger UI的描述信息 version: 1.0.0 # Swagger UI的版本信息 base-package: com.example.demo.controller # 扫描API文档所在的controller包 ``` 3、编写API文档 在Java开发中,通常通过注解的方式来提供API文档。Swagger3.0也不例外,它提供了一些注解,用于描述API的基本信息、请求参数、响应参数等。举个例子,下面是一个简单的UserController,其中涉及了Swagger3.0的注解: ```java @RestController @RequestMapping("/user") public class UserController { @ApiOperation(value = "获取用户详细信息", notes = "根据用户的ID来获取用户详细信息") @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "int", paramType = "path") @GetMapping("/{id}") public User getUser(@PathVariable int id) { // 根据id获取用户信息 return user; } } ``` 其中,@ApiOperation注解用于描述API接口的基本信息,包括接口名称、接口说明等;@ApiImplicitParam注解则用于描述请求参数的基本信息,包括参数名称、参数类型、是否必填等。 4、访问Swagger UI 在完成上述步骤之后,我们就可以访问Swagger UI了。默认情况下,Swagger UI的URL为http://localhost:8080/swagger-ui/index.html,其中8080是Spring Boot应用的端口号,可以根据实际情况进行调整。在Swagger UI中,可以看到所有API接口的详细信息,包括请求参数、响应参数等。 总结 通过上述步骤,我们就可以在Spring Boot集成Swagger3.0,方便的生成API文档并提供可视化的UI来测试API。在真实的开发环境中,我们可以根据实际需求来调整Swagger3.0的配置,以便更好的满足我们的开发需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值