swagger

本文详细介绍如何在Java项目中整合JPA与Swagger,实现RESTful API的自动生成与维护,包括依赖添加、配置文件编写、接口定义及响应设置等关键步骤。

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

一、JPA简介
目前前后端分离开发已经成为一种主流开发方式。
这种开发方式中一部分开发人员只做前端开发(app开发),另一部分开发人员只做后端开发。
开发过程中的沟通就很重要了。
所以通如何进行呢?
api文档是最好的沟通方式。
但是有了api文档,如果接口发生变化,不能及时更新,更新了又没有及时通知,就会在前后端项目联调中爆发出很多问题

Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。

  1. 及时性 (接口变更后,能够及时准确地通知相关前后端开发人员)
  2. 规范性 (并且保证接口的规范性,如接口的地址,请求方式,参数及响应格式和错误信息)
  3. 一致性 (接口信息一致,不会出现因开发人员拿到的文档版本不一致,而出现分歧)
  4. 可测性 (直接在接口文档上进行测试,以方便理解业务)

二、整合
1、添加依赖

  <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger2</artifactId>
      <version>2.7.0</version>
  </dependency>
        
  <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger-ui</artifactId>
      <version>2.7.0</version>
  </dependency>

2、创建Swagger配置类

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;


@Configuration
@EnableSwagger2
public class SwaggerConfig {
    //@Value("${server.context-path}")
    //private String apiPath;
    @Bean
    public Docket apiConfig() {
        return new Docket(DocumentationType.SWAGGER_2);
    }
}

3、重启服务访问api文档 swagger-ui.html
4、配置api的基本信息

@Bean
    public Docket apiConfig() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("api")//定义分组
                .apiInfo(apiInfo())// 调用apiInfo方法,创建一个ApiInfo实例,里面是展示在文档页面信息内容
                .useDefaultResponseMessages(false);//不使用默认的返回值
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
               .title("BookStore Platform API")//大标题
                .description("BookStore Platform's REST API, all the applications could access the Object model data via JSON.")//详细描述
                .version("1.0")//版本
                .contact(new Contact("", "", "@163.com"))//作者
                .license("The Apache License, Version 2.0")//许可证信息
                .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")//许可证地址
                .build();
    }

5、接口过滤

@Bean
    public Docket apiConfig() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("api")//定义分组
                .apiInfo(apiInfo())// 调用apiInfo方法,创建一个ApiInfo实例,里面是展示在文档页面信息内容
                .useDefaultResponseMessages(false)//不使用默认的返回值
                .select()//创建ApiSelectorBuilder对象
                .paths(Predicates.or(PathSelectors.regex("/api2/.*")))//过滤的接口
                .build();
    }

三、定义接口
1、定义资源接口

@RestController
@RequestMapping("api2")
@Api(description="书籍管理的CRUD")//对api资源的描述(热部署不好使)
public class BookController2 {

    @Autowired
    private BookService bookService;

    @GetMapping("books")
    @ApiOperation(value = "图书列表", notes = "获取全部图书列表")
    public List<Book> getBookList(){
       return bookService.getBookList();
    }

2、定义模型数据

@Entity
@ApiModel
public class Book implements Serializable{

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @ApiModelProperty(hidden=true)
    private Long bookId;

    @ApiModelProperty(name="bookName",value="图书标题",required=true,example="深入理解Java虚拟机")
    private String bookName;

    @ApiModelProperty(name="isbn",value="ISBN",required=false,example="9787111421900")
    private String isbn;

    @ApiModelProperty(name="publisher",value="出版社",required=false,example="机械工业出版社")
    private String publisher;

3、定义响应

@GetMapping("books/{id}")
@ApiOperation(value = "获取图书", notes = "根据id获取图书信息")
@ApiResponses({
        @ApiResponse(code = -1, message = "数据不存在")
})
public Book getBookById(@PathVariable("id") Long id){
    return bookService.getBookById(id);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值