当前位置:网站首页>不用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"));
}
边栏推荐
- 读懂这6本书,学习MySQL更轻松
- Explanation of JDBC classes
- Two years of crud, two graduates, two months of preparation for the interview with ALI, and fortunately won the offer grading p6
- 吊打面试官的问题
- 表格数据处理软件,除了Excel还有什么?
- RHEL 6.4 安装svn和apache
- Understanding of the return value of the structure pointer function passed to the structure pointer
- Why should coding and modulation be carried out before transmission
- Header library file
- Install MySQL based on docker
猜你喜欢

用手机对电脑进行远程关机

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

Installation points and precautions of split angle probe

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

10_ UE4 advanced_ Add fall and cast actions

Remote shutdown of computer with mobile phone

Blue Bridge Cup embedded Hal library LCD

float浮动初步理解

Redis-day01 common sense supplement and redis introduction

Blue Bridge Cup embedded Hal library systick
随机推荐
做数据分析,你还不懂RFM分析方法(模型)?
Explanation of JDBC classes
Clo********e: project management notes
Using k-means clustering to classify tariff models of different industries
Under the platform driven platform, the "dev- > dev.of_node" of the formal parameter dev in the probe function Understanding of
Nodejs: return value of mongodb after successful insertion
零代码 | 轻松实现数据仓库建模,搭建BI看板
Make a virtual human with zego avatar | virtual anchor live broadcast solution
网络文件系统服务(NFS)
Use the statement object to execute DDL statements to create tables
什么是WordPress
数组相关的知识点
Picture slide effect
Build a quick development ide: visualsvn + sublime + Visual Studio 2013 + quickeasyftpserver
Here is a super practical excel shortcut set (common + summary of eight categories)
ThinkPad指纹验证在win7无法使用的解决方法
The 10th Landbridge cup embedded electronic provincial competition
nodejs:检测并安装npm模块,如果已安装则跳过
Arduino基础知识
用手机对电脑进行远程关机