当前位置:网站首页>不用Swagger,那我用啥?
不用Swagger,那我用啥?
2022-07-28 10:45:00 【InfoQ】
1. OpenApi
- SpringFox
- SpringDoc
- OpenAPI 3
- Spring-boot,全版本都支持。
- JSR-303 中提供的一些注解,例如
@NotNull、@Min、@Max以及@Size等。
- Swagger-ui:SpringDoc 提供的接口 JSON 也可以通过 Swagger-ui 展示出来。
- OAuth 2
- ...
2. 引入 SpringDoc
- 生成接口文档 JSON。
- 渲染接口文档 JSON。
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-webmvc-core</artifactId>
<version>1.6.9</version>
</dependency>

<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.6.9</version>
</dependency>

/v3/api-docs- /v3/api-docs
- /swagger-ui/index.html
springdoc.swagger-ui.path=/javaboy-ui
springdoc.api-docs.path=/javaboy-api
3. 结合 Spring Security
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello(@AuthenticationPrincipal User user) {
System.out.println("user = " + user);
return "hello";
}
}
@AuthenticationPrincipal<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-security</artifactId>
<version>1.6.9</version>
</dependency>
4. 结合 Spring Data Rest
4.1 Spring Data Rest
创建工程
WebJpaMySQLRest Repositories
配置数据库
spring.datasource.username=root
spring.datasource.password=1234
spring.datasource.url=jdbc:mysql:///test02?serverTimezone=Asia/Shanghai
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.database=mysql
spring.jpa.database-platform=mysql
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL57Dialect
构建实体类
@Entity(name = "t_book")
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "book_name")
private String name;
private String author;
//省略 getter/setter
}
public interface BookRepository extends JpaRepository<Book,Long> {
}
测试
- http://127.0.0.1:8080/books/{id}

- http://127.0.0.1:8080/books


- size 表示每页查询记录数
- totalElements 表示总记录数
- totalPages 表示总页数
- number 表示当前页数,从0开始计
http://127.0.0.1:8080/books?page=1&size=3&sort=id,desc



查询定制
public interface BookRepository extends JpaRepository<Book,Long> {
List<Book> findBookByAuthorContaining(@Param("author") String author);
}


public interface BookRepository extends JpaRepository<Book, Long> {
@RestResource(rel = "byauthor",path = "byauthor")
List<Book> findBookByAuthorContaining(@Param("author") String author);
}
- rel 表示接口查询中,这个方法的 key
- path 表示请求路径

relpath@RestResourceexportedtrueexportedfalseid@RestResourcepublic interface BookRepository extends JpaRepository<Book, Long> {
@RestResource(rel = "byauthor",path = "byauthor")
List<Book> findBookByAuthorContaining(@Param("author") String author);
@Override
@RestResource(exported = false)
void deleteById(Long aLong);
}
item@RepositoryRestResource(collectionResourceRel = "bs",itemResourceRel = "b",path = "bs")
public interface BookRepository extends JpaRepository<Book, Long> {
@RestResource(rel = "byauthor",path = "byauthor")
List<Book> findBookByAuthorContaining(@Param("author") String author);
@Override
@RestResource(exported = false)
void deleteById(Long aLong);
}
path其他配置
spring.data.rest.base-path=/api
spring.data.rest.sort-param-name=sort
spring.data.rest.page-param-name=page
spring.data.rest.limit-param-name=size
spring.data.rest.max-page-size=20
spring.data.rest.default-page-size=0
spring.data.rest.return-body-on-update=true
spring.data.rest.return-body-on-create=true
- 给所有的接口添加统一的前缀
- 配置排序参数的 key ,默认是 sort
- 配置分页查询时页码的 key,默认是 page
- 配置分页查询时每页查询页数的 key,默认是size
- 配置每页最大查询记录数,默认是 20 条
- 分页查询时默认的页码
- 更新成功时是否返回更新记录
- 添加成功时是否返回添加记录
4.2 生成接口文档
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-data-rest</artifactId>
<version>1.6.9</version>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.6.9</version>
</dependency>

5. 结合 Actuator
springdoc.show-actuator=true

springdoc.use-management-port=true
management.endpoints.web.exposure.include=openapi, swagger-ui
management.server.port=9090
- http://localhost:9090/actuator/swagger-ui/index.html

6. 切换到 Swagger
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.6.9</version>
</dependency>
- @Api → @Tag
- @ApiIgnore → @Parameter(hidden = true) or @Operation(hidden = true) or @Hidden
- @ApiImplicitParam → @Parameter
- @ApiImplicitParams → @Parameters
- @ApiModel → @Schema
- @ApiModelProperty(hidden = true) → @Schema(accessMode = READ_ONLY)
- @ApiModelProperty → @Schema
- @ApiOperation(value = "foo", notes = "bar") → @Operation(summary = "foo", description = "bar")
- @ApiParam → @Parameter
- @ApiResponse(code = 404, message = "foo") → @ApiResponse(responseCode = "404", description = "foo")
@Bean
public Docket publicApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("org.github.springshop.web.public"))
.paths(PathSelectors.regex("/public.*"))
.build()
.groupName("springshop-public")
.apiInfo(apiInfo());
}
@Bean
public Docket adminApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("org.github.springshop.web.admin"))
.paths(PathSelectors.regex("/admin.*"))
.apis(RequestHandlerSelectors.withMethodAnnotation(Admin.class))
.build()
.groupName("springshop-admin")
.apiInfo(apiInfo());
}
@Configuration
public class SpringDocConfig {
@Bean
public GroupedOpenApi publicApi() {
return GroupedOpenApi.builder()
.group("springshop-public")
.pathsToMatch("/public/**")
.build();
}
@Bean
public GroupedOpenApi adminApi() {
return GroupedOpenApi.builder()
.group("springshop-admin")
.pathsToMatch("/admin/**")
.addOpenApiMethodFilter(method -> method.isAnnotationPresent(RequestMapping.class))
.build();
}
}
springdoc.packages-to-scan=org.javaboy.spring_doc.controller
springdoc.paths-to-match=/**
@Bean
OpenAPI springShopOpenAPI() {
return new OpenAPI()
.info(new Info().title("江南一点雨")
.description("Spring Boot 教程")
.version("v0.0.1")
.license(new License().name("Apache 2.0").url("http://www.javaboy.org")))
.externalDocs(new ExternalDocumentation()
.description("一些描述信息")
.url("https://github.com/lenve/vhr"));
}
边栏推荐
- Blue Bridge Cup embedded Hal library USART_ TX
- Learn how to do e-commerce data analysis (with operation analysis index framework)
- leetcode:981. 基于时间的键值存储【迭代for的陷阱:on】
- Tree Shaking和DCE
- 关于结构体指针函数的返回值传递给结构体指针的理解
- cortex-M4与cortex-A7内核启动流程分析
- 内存操作函数memcpy()和memmove()的用法
- 2021-03-24
- Learn these analysis methods and models, and no longer have no ideas when encountering problems
- 用 ZEGO Avatar 做一个虚拟人|虚拟主播直播解决方案
猜你喜欢

Do you want to enroll in class for advanced soft exam

10_ UE4 advanced_ Add fall and cast actions

Zero code | easily realize data warehouse modeling and build Bi Kanban

读懂这6本书,学习MySQL更轻松

用 ZEGO Avatar 做一个虚拟人|虚拟主播直播解决方案

float浮动初步理解

低代码十问:一文讲透关于低代码的一切!

Configuring raspberry pie, process and problems encountered

低代码(aPaas)为什么最近又火了?

一文学会如何做电商数据分析(附运营分析指标框架)
随机推荐
哈希表的相关知识点
CGAL compilation error
Sword finger offer 06. print linked list from end to end
Bc35 NB module at instruction development summary
Remote shutdown of computer with mobile phone
Blue Bridge Cup embedded Hal library systick
5. Implement MapReduce program on window side to complete wordcount function
6. MapReduce custom partition implementation
Here is a super practical excel shortcut set (common + summary of eight categories)
Understanding of the return value of the structure pointer function passed to the structure pointer
Yan reported an error: could not find any valid local directory for nmprivate/
做数据分析,你还不懂RFM分析方法(模型)?
nodejs:mongodb 插入成功之后的返回值
Installation points and precautions of split angle probe
Generation and use of Lib library files in keil and IAR
Purchase, sale and inventory software suitable for small and medium-sized enterprises to solve five major problems
Blue Bridge Cup embedded Hal library USART_ RX
Install GMP
Use the statement object to execute DDL statements to create tables
3. MapReduce explanation and source code analysis