当前位置:网站首页>No swagger, what do I use?
No swagger, what do I use?
2022-07-28 21:56:00 【JavaShark】
1. OpenApi
In formal study Spring Doc Before , Let me introduce you to OpenAPI.
OpenApi It's an industry API Document standard , It's a norm , This specification currently has two major implementations , Namely :
- SpringFox
- SpringDoc
among SpringFox In fact, it is what we said before Swagger,SpringDoc Is what we are going to say today .
OpenApi It's like JDBC equally , Various specifications have been formulated , and Swagger and SpringDoc It is similar to all kinds of database drivers , It's a concrete realization .
So many friends may also find ,Swagger and Spring Doc There are some similarities , This is because they all abide by the same norms .
But what? ,Swagger The update is a little slow , In order to be able to communicate with the new version Spring Boot Integrate , still SpringDoc It's more worth experiencing .
SpringDoc Support :
- OpenAPI 3
- Spring-boot, All versions support .
- JSR-303 Some comments provided in , for example @NotNull、@Min、@Max as well as @Size etc. .
- Swagger-ui:SpringDoc Provided interface JSON It can also be done through Swagger-ui display .
- OAuth 2
- ...
2. introduce SpringDoc
My friends know , This tool for generating interface documents , Generally speaking, it has two functions :
- Generate interface document JSON.
- Render interface documentation JSON.
therefore , When we use SpringDoc When , If you just want to generate interface documents JSON, Then just add the following dependencies :
<dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-webmvc-core</artifactId> <version>1.6.9</version> </dependency>
here , The interface will be automatically generated for the interface in the project JSON file , Similar to the following :
In this way JSON Information developers can draw it by themselves , You can also use some ready-made tools on the Internet, such as Knife4j And so on. . Of course, if you don't want to bother , You can also use SwaggerUI Draw it , If you want to use web pages , Then don't use the above dependencies , Use the following dependency , Not only can you generate JSON Interface , You can also generate rendered web pages :
<dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-ui</artifactId> <version>1.6.9</version> </dependency>
The effect of the web page is shown in the figure below :
This web page looks familiar , In fact, that is Swagger UI.
There is an input box on this page , The input is /v3/api-docs, This address is what this web page wants to render JSON The address of , If the developer modifies the generated JSON API The address of the document , Then you need to manually enter in this input box JSON API The address of the document .
default JSON API The document address is :
- /v3/api-docs
Default web page UI The address is :
- /swagger-ui/index.html
If you need to configure , Can be in Spring Boot Of application.properties Directly configure :
springdoc.swagger-ui.path=/javaboy-ui springdoc.api-docs.path=/javaboy-api
However, these two configurations do not really change the access path , These two are equivalent to taking an alias for the access path , When accessing these two, it will automatically redirect to the corresponding path .
3. combination Spring Security
If we use Spring Security, Then the parameters of some interfaces may be special , For example, the following interface :
@RestController public class HelloController { @GetMapping("/hello") public String hello(@AuthenticationPrincipal User user) { System.out.println("user = " + user); return "hello"; } }
The parameter of this interface is added with @AuthenticationPrincipal The annotation indicates the user object that is currently logged in successfully , This parameter is used in practice , Front end delivery is not required , The server will automatically inject this parameter .
however ! If used SpringDoc, When calling this interface through a web page , This parameter must be passed , For this kind of problem , We can introduce the following dependencies to help us solve them automatically :
<dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-security</artifactId> <version>1.6.9</version> </dependency>
This dependency will automatically help us ignore the interface with @AuthenticationPrincipal Annotated parameters , So we're going through swagger-ui There is no need to pass this parameter when conducting interface testing .
4. combination Spring Data Rest
Spring Boot Provided in Spring Data Rest, combination Jpa It is very convenient to build Restful application . But this kind of Restful Applications don't need developers to write their own interfaces , So how to generate interface documents ( I don't know where the connector is )? For this ,SpringDoc It also provides relevant support , Let's see .
4.1 Spring Data Rest
Create a project
First create a Spring Boot engineering , introduce Web 、 Jpa 、 MySQL 、Rest Repositories rely on :
Configuration database
There are two main configurations , One is the database , The other is Jpa:
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
The configuration here , and Jpa Is basically the same as .
The first three lines configure the basic information of the database , Including database connection pool 、 Database user name 、 Database password 、 Database connection address and database driver name .
The next five elements are configured JPA Basic information of , They represent generation SQL Dialect of 、 Print the birth of SQL 、 Choose whether to update the table according to the actual situation each time you start the project 、 The database platform is MySQL.
These two configurations are about MySQL + JPA Configuration of , Never used JPA You can refer to song GE's previous JPA article :http://www.javaboy.org/2019/0407/springboot-jpa.html
Build entity classes
@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; // Omit getter/setter } public interface BookRepository extends JpaRepository<Book,Long> { }
One is to configure an entity class Book, The other is to configure a BookRepository , After the project starts successfully , The framework will be based on Book The definition of a class , Automatically create the corresponding tables in the database ,BookRepository Interface is inherited from JpaRepository ,JpaRepository Some basic methods of adding, deleting, modifying and checking are included in .
Okay , The code is finished .
what ? You don't seem to have written anything ? Yes , Nothing , Don't write anything , One RESTful Add, delete, modify and check the application of style , This is it. Spring Boot The charm of !
test
here , We can start the project for testing , Use POSTMAN To test ( You can also choose what you want HTTP Request tool ).
At this time, our project has some interfaces by default , Let's look at :
according to id Query interface
- http://127.0.0.1:8080/books/{id}
This interface is based on id Search for a book :
Paging query
- http://127.0.0.1:8080/books
This is a batch query interface , The default request path is lowercase , And one more s suffix . This interface is actually a paging query interface , No parameters passed , Means to query the first page , each page 20 Data .
In the query results , In addition to the data that should be available , It also contains paging data :
In paging data :
- size Indicates the number of query records per page
- totalElements Indicates the total number of records
- totalPages Indicates the total number of pages
- number Indicates the current number of pages , from 0 Starting meter
If you want to page or sort queries , have access to _links Link in .http://127.0.0.1:8080/books?page=1&size=3&sort=id,desc .
add to
You can also add data , Add yes POST request , Data is passed through JSON Form transfer , as follows :
After adding successfully , By default, the added data will be returned .
modify
Modifying the interface by default also exists , The data modification request is a PUT request , The modified parameters are also passed JSON Form transfer :
By default , After modification , The modified data will be returned .
Delete
Of course, it can also be DELETE The request is based on id Delete data :
After deleting successfully , There is no return value .
It doesn't take a few lines of code , A basic addition, deletion, modification and search is available .
These are the default configurations , These default configurations are in fact JpaRepository On the basis of implementation , In actual projects , We can also customize these functions .
Query customization
The most extensive customization , It's a query , Because the changes of add, delete and change operations are not as rich as queries . Customization of query , Very easy to , Just provide relevant methods . For example, search books according to the author :
public interface BookRepository extends JpaRepository<Book,Long> { List<Book> findBookByAuthorContaining(@Param("author") String author); }
Be careful , Method definition , Parameters should have @Param annotation .
After customization , Restart project , Now there is an additional query interface , Developers can use http://localhost:8080/books/search To see and book What are the relevant custom interfaces :
The query result indicates , There is only one custom interface , The interface name is the method name , And the query results also give an example of the interface call . Let's try to call our own query interface :
According to the actual situation, developers can , stay BookRepository Any number of query methods are defined in , Definition rules and Jpa It's as like as two peas ( Don't understand, Jpa Little buddy , Refer to dry goods | Article to read Spring Data Jpa!, Or on SongGe's personal website www.javaboy.org On the search JPA, There are related tutorials for reference ). however , There is a flaw in this , Namely Jpa Middle method name is too long , therefore , If you don't want to use the method name as the interface name , Then you can customize the interface name :
public interface BookRepository extends JpaRepository<Book, Long> { @RestResource(rel = "byauthor",path = "byauthor") List<Book> findBookByAuthorContaining(@Param("author") String author); }
@RestResource In the annotations , The meaning of two parameters :
- rel Indicates in the interface query , This method is key
- path Indicates the request path
When this definition is complete , Indicates that the interface name is byauthor , Restart project , Continue to query interfaces :
except rel and path Besides two attributes ,@RestResource There is another property in ,exported Indicates whether the interface is exposed , The default is true , Indicates the exposed interface , That is, methods can be called at the front end , If you just want to define a method , You don't need to call this method on the front end , You can set exported The attribute is false .
If you don't want to expose officially defined methods , For example, according to id Delete data , Just rewrite the method in the custom interface , Then add... To the method @RestResource Annotate and configure the properties .
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); }
Additionally generated JSON Set name and single... In string item The names of are all customizable :
@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 Property indicates the request path , The request path is lowercase by default +s, You can redefine it here .
Other configuration
Last , It can also be in application.properties Middle configuration REST The basic parameters :
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
Configuration meaning , From the top down , In turn, is :
- Add a uniform prefix to all interfaces
- Configure the sort parameters key , The default is sort
- Configure the page number when paging query key, The default is page
- Configure the number of pages to be queried per page during paging query key, The default is size
- Configure the maximum number of query records per page , The default is 20 strip
- Default page number for paging query
- Whether to return the update record when the update is successful
- Whether to return to add record when adding successfully
This is a Spring Data Rest A simple use of , Next, let's look at how to generate this document .
4.2 Generate interface document
For this kind of interface you haven't seen , We only need to add the following dependencies , It can automatically generate API Document. , as follows :
<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>
The generated interface document is as follows :
5. combination Actuator
Prior to Spring Boot tutorial , Brother song also introduced to you Spring Boot Medium actuator, This tool can generate the endpoint of project operation data by itself (endpoints), If you want to include these endpoints SpringDoc In the to , Then just add the following configuration :
springdoc.show-actuator=true
as for SpringDoc How many will be displayed Actuator End point out , It depends on Actuator How many endpoints are exposed , The final display effect is as follows :
But there is another way to play !
SpringDoc After all, the role played is not a business function , But the auxiliary function of the project , therefore , We can separate it from our business , Put it in Actuator in , After all Actuator Specialize in such things . Then you only need to add the following two configurations :
springdoc.use-management-port=true management.endpoints.web.exposure.include=openapi, swagger-ui management.server.port=9090
When the configuration is complete , In the future, we can Actuator Go to view the interface document and the corresponding page , The address is :
- http://localhost:9090/actuator/swagger-ui/index.html
6. Switch to Swagger
If you have used Swagger 了 , Then you can also switch to SpringDoc Up here , When switching , First introduce SpringDoc rely on :
<dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-ui</artifactId> <version>1.6.9</version> </dependency>
Swagger and SpringDoc The corresponding relationship of notes is as follows :
- @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")
We used to Swagger The way to configure interface scanning in is as follows :
@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()); }
Now in SpringDoc You can configure it in the following way ( You can also mark the methods that need to generate interface documents according to the annotations ):
@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(); } }
Of course , If you don't need to group interface documents , Then you can also not use Java To configure , Directly in application.properties You can configure it in :
springdoc.packages-to-scan=org.javaboy.spring_doc.controller springdoc.paths-to-match=/**
stay SpringDoc in , If you want to configure Swagger UI, You can configure it in the following ways :
@Bean OpenAPI springShopOpenAPI() { return new OpenAPI() .info(new Info().title(" A little rain in Jiangnan ") .description("Spring Boot course ") .version("v0.0.1") .license(new License().name("Apache 2.0").url("http://www.javaboy.org"))) .externalDocs(new ExternalDocumentation() .description(" Some descriptive information ") .url("https://github.com/lenve/vhr")); }
边栏推荐
- 基于多模态融合的非遗图片分类研究
- 面向千元级5G手机市场,联发科天玑700发布
- SkiaSharp 之 WPF 自绘 拖曳小球(案例版)
- Library borrowing system "suggested collection"
- How to search images efficiently and accurately? Look at the lightweight visual pre training model
- 系统分析师
- 针对下一代Chromebook,联发科推出新款芯片组MT8192和MT8195
- [英雄星球七月集训LeetCode解题日报] 第28日 动态规划
- The general strike of three factories in St France may make the shortage of chips more serious!
- 1162. Map analysis - non recursive method
猜你喜欢
What technology is needed for applet development
kali里的powersploit、evasion、weevely等工具的杂项记录
Kubedm builds kubernetes cluster
详解visual studio 2015在局域网中远程调试程序
中国农业工程学会农业水土工程专业委员会-第十二届-笔记
PyQt5快速开发与实战 5.4 网页交互
LeetCode链表问题——面试题02.07.链表相交(一题一文学会链表)
Leetcode interview question 02.07. Linked list intersection [knowledge points: Double pointers, stack]
Nano gold coupled antibody / protein Kit (20nm, 1mg/100 μ g/500 μ G coupling amount) preparation
Which brand is the best and most cost-effective open headset
随机推荐
Record some small requirements in the form of cases
网格数据生成函数meshgrid
【英雄哥七月集训】第 28天:动态规划
The University was abandoned for three years, the senior taught himself for seven months, and found a 12K job
Cross domain transfer learning of professional skill word extraction in Chinese recruitment documents
Huawei releases the first electric drive system driveone: charging for 10 minutes, endurance of 200km
Mesh data generation function meshgrid
世界肝炎日 | 基层也能享受三甲资源,智慧医疗系统如何解决“看病难”?
How to search images efficiently and accurately? Look at the lightweight visual pre training model
Storage and steps of phospholipid coupled antibody / protein Kit
聊一聊数据库的行存与列存
Cy3/cy5/cy5.5/cy7 fluorescent labeling antibody / protein Kit (10~100mg labeling amount)
1162. Map analysis - non recursive method
Open earphone which air conduction earphone with good sound quality and recognized sound quality is recommended
节省70%的显存,训练速度提高2倍!浙大&阿里提出在线卷积重新参数化OREPA,代码已开源!(CVPR 2022 )
Apifox:满足你对 Api 的所有幻想
An end-to-end aspect level emotion analysis method for government app reviews based on brnn
Wechat applet development company, do you know how to choose?
针对下一代Chromebook,联发科推出新款芯片组MT8192和MT8195
Skiasharp's WPF self drawn drag ball (case version)