Swagger配置

本文介绍了如何在SpringBoot项目中集成Swagger工具,包括添加依赖、配置Swagger2、解决版本冲突及静态资源问题,最后展示了如何通过浏览器访问SwaggerUI进行API测试。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Swagger是一套用于创建、描述和测试RESTful风格的Web服务的工具和框架。它能够自动生成详尽的API文档,并在后台代码更新时自动同步更新文档内容。此外,Swagger还提供了一个完整的测试页面,可用于调试API。

配置Swagger有以下步骤:
1、在pom文件中添加依赖

    <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、添加config配置类

//Swagger配置


package com.example.helloword.config;

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 //告诉Spring 容器,这个类是一个配置类
@EnableSwagger2 //启用Swagger2功能
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com"))   //扫描哪个包
                .paths(PathSelectors.any()).build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("演示项目API")//标题
                .description("学习Swagger2的演示项目")//描述
                .version("1.0")//版本
                .build();
    }
}

3、在application.properties中添加

#Springboot2.6.x后与Swagger有版本冲突问题,需要在application.properties中加入以下配置
spring.mvc.pathmatch-startegy=ant_path_matter

注意:在application.properties中如果有设置静态资源目录的需注释下,之前我就是因为静态资源过滤的原因导致在服务器打不开swagger

#spring.mvc.static-path-pattern=/images/**
#spring.web.resources.static-locations = classpath:/css

4、在浏览器输入http://localhost:8080/swagger-ui.html,即可访问swagger的ui界面(我的服务器端口是8080,一般springboot默认为8080端口),在ui界面可以查看自己的controller接口

### 配置 Swagger 在项目中的使用 在 Spring Boot 项目中,可以通过多种方式配置 Swagger 来生成和管理 API 文档。以下是详细的配置步骤: #### 1. 引入依赖 首先,在项目的 `pom.xml` 文件中添加 Swagger 的依赖。通常使用的是 `springfox-swagger2` 和 `springfox-swagger-ui` 库[^2]。 ```xml <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. 创建 Swagger 配置类 接下来,创建一个 Java 配置类来启用和配置 Swagger。该类需要与 Spring Boot 的启动类处于同一层级或其子包中。 ```java package org.springboot; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import io.swagger.annotations.ApiOperation; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket swaggerSpringMvcPlugin() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) .build(); } } ``` 上述代码启用了 Swagger,并通过 `Docket` Bean 定义了文档的生成规则。这里选择仅扫描带有 `@ApiOperation` 注解的方法 [^4]。 #### 3. 配置跨域支持(可选) 如果前端应用与后端服务不在同一个域名下,需要配置跨域支持。可以在 `SwaggerConfig` 类中添加以下方法: ```java @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/v2/api-docs/**") .allowedOrigins("*") .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS"); } }; } ``` #### 4. 使用 Swagger 注解 在控制器类和方法上使用 Swagger 注解,以提供更详细的文档信息。常见的注解包括: - **`@ApiModel`**:用于描述模型对象。 - **`@ApiModelProperty`**:用于描述模型属性。 - **`@Api`**:用于描述控制器类的功能。 - **`@ApiOperation`**:用于描述具体的操作。 示例代码如下: ```java @Api(tags = "用户信息") @RestController @RequestMapping("/users") public class UserController { @ApiOperation(value = "查询用户详细信息") @GetMapping("/{id}") public User getUserById(@PathVariable Long id) { // 方法实现 } } ``` #### 5. 启动并访问 Swagger UI 完成上述配置后,启动 Spring Boot 应用程序,并通过以下 URL 访问 Swagger UI: ``` http://localhost:8080/swagger-ui.html ``` 在这个界面中,可以查看所有已定义的 API 接口,并进行测试。 #### 6. 安全控制(可选) 为了增强安全性,可以为 Swagger 配置权限验证。例如,使用 Spring Security 对 `/swagger-ui.html` 路径进行保护: ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/swagger-ui.html").authenticated() .and() .httpBasic(); // 使用 HTTP Basic 认证 } } ``` 通过这种方式,只有经过认证的用户才能访问 Swagger UI 界面 [^1]。 ---
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值