SpringBoot 配置Swagger3.0接口文档

本文介绍了如何在SpringBoot项目中集成Swagger3.0.0,包括在pom.xml中添加依赖,创建SwaggerConfig配置类,指定接口路径,以及如何在控制器中使用@Api和@ApiModel注解来生成API文档。最后提供访问SwaggerUI的地址。

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

1. Swagger配置类 

第一步,需要在pom中引入相应的配置,这里使用的是3.0.0版本,SpringBoot使用的2.5.9 版本。

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

第二步

在代码中加入相应的配置,新建config包,写入SwaggerConfig配置类:

package com.cheng.springboot.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.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

@Configuration
public class SwaggerConfig {

    @Bean
    public Docket docket() {
        return new Docket(DocumentationType.SWAGGER_2)
//                .groupName("标准接口")
                .apiInfo(apiInfo())
                .useDefaultResponseMessages(true)
                .forCodeGeneration(false)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.cheng.springboot.controller"))
                .paths(PathSelectors.any())
                .build();


    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title("测试接口文档")
//                .description("认识接口文档")
//                .termsOfServiceUrl("...地址")
//                .contact(new Contact("cheng","htt","邮箱"))
                .version("1.0")
                .build();
    }

}

.apis(RequestHandlerSelectors.basePackage(“com.cheng.springboot.controller”))这个配置是用来指定我们的接口层的位置,大家可以根据你自己项目的实际情况来进行修改。.apiInfo()是定义一些我们项目的描述信息,可以根据实际需要在参数中修改。需要注意的是配置类的头部需要加上@Configuration。

2. 使用swagger

package com.cheng.springboot.controller;


import com.cheng.springboot.entity.User;
import com.cheng.springboot.mapper.UserMapper;
import com.cheng.springboot.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@AllArgsConstructor
@Api(value = "用户管理",tags = {"用户相关接口"})
@RequestMapping("/user")
public class UserController {

    private final UserMapper userMapper;
    private final UserService userService;

    @PostMapping("/insert")
    @ApiOperation(value = "添加用户")
    public boolean save(@RequestBody  User user){
        return  userService.saveUser(user);
    }

    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "删除用户")
    public Integer delete(@ApiParam(name="id",value="用户id",required=true) @PathVariable Integer id){
       return userMapper.deleteById(id);
    }

    // 分页查询
    // @RequestParam接收
    // limit第一个参数(pagenum-1)*pageSize

    @GetMapping("/page")
    @ApiOperation(value = "查询用户(分页)")
    public Map<String, Object> index(@ApiParam(name="pageNum",value="页码",required=true) @RequestParam Integer pageNum,@ApiParam(name="pageSize",value="每页几条",required=true) @RequestParam Integer pageSize){
        pageNum = (pageNum-1)*pageSize;
        Integer total = userMapper.selectTotal();
        Map<String, Object> res = new HashMap<>();
        List<User> data = userMapper.selectPage(pageNum, pageSize);
        res.put("data",data);
        res.put("total",total);
        return res;
    }
}

实体类中如何使用?

@ApiModel注解是用在接口相关的实体类上的注解,它主要是用来对使用该注解的接口相关的实体类添加额外的描述信息,常常和@ApiModelProperty注解配合使用

@ApiModelProperty注解则是作用在接口相关实体类的属性(字段)上的注解,用来对具体的接口相关实体类中的参数添加额外的描述信息,除了可以和 @ApiModel 注解关联使用,也会单独拿出来用。

作用域不同,@ApiModel作用在类上,@ApiModel作用来属性上

package com.cheng.springboot.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.Data;

@Data
@TableName(value = "user")
@ApiModel("userDTO")
public class User {
    @ApiModelProperty("用户id")
    @TableId(type = IdType.AUTO)
    private Integer id;
    @ApiModelProperty("用户名")

    private String username;
    @ApiModelProperty("密码")

    @JsonIgnore
    private String password;
    @ApiModelProperty("昵称")

    private String nickname;
    @ApiModelProperty("邮箱")

    private String email;
    @ApiModelProperty("手机号")

    private String phone;
    @TableField(value = "address")
    @ApiModelProperty("地址")

    private String address;

}

访问地址:http://localhost:9091/swagger-ui/index.html 

### 回答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-ui.contact.email=support@mycompany.com 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可帮助我们大大提高开发效率和减少错误。 ### 回答3Swagger是一个开源的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,其中8080Spring Boot应用的端口号,可以根据实际情况进行调整。在Swagger UI中,可以看到所有API接口的详细信息,包括请求参数、响应参数等。 总结 通过上述步骤,我们就可以在Spring Boot中集成Swagger3.0,方便的生成API文档并提供可视化的UI来测试API。在真实的开发环境中,我们可以根据实际需求来调整Swagger3.0配置,以便更好的满足我们的开发需求。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

成序猿@

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值