当前位置:网站首页>Swagger 3.0 brushes the screen every day. Does it really smell good?
Swagger 3.0 brushes the screen every day. Does it really smell good?
2020-11-06 20:13:00 【itread01】
Continuous original output , Click on the blue word above to follow me

Catalog
-
Preface -
How to say official documents ? -
Spring Boot Version Description -
New dependencies -
springfox-boot-starter What has been done ? -
Rolling up your sleeves is dry ? -
Customize a basic file example -
How files are grouped ? -
How to add authorization information ? -
How to carry public request arguments ?
-
-
It's a rough one BUG -
Summary
Preface
Recently, it has been frequently affected by Swagger 3.0
refresh , Officials say it's a breakthrough change , There are a lot of highlights , I don't really believe , Today, I'd like to show you some fresh food , Let's see if the soup is fresh or not ....
How to say official documents ?
The project is open source in Github
On , Address :https://github.com/springfox/springfox.
Swagger 3.0
What are the changes ? The official documents summarize the following :
-
Deleted the springfox-swagger2
The dependence of -
Delete all @EnableSwagger2...
Notes -
Added springfox-boot-starter
Dependencies -
Removed guava
Third party dependence -
File access address changed , Changed to http://ip:port/project/swagger-ui/index.html
.
Let's see here , How do you feel at first ?

Now that someone else has updated it , We can't help it , I 'll introduce you to Spring Boot
How to integrate Swagger 3.0
Well .
Spring Boot Version Description
Author use Spring Boot
The version is 2.3.5.RELEASE
New dependencies
Swagger 3.0
We already have Spring Boot Integrated starter , Just add the following dependencies :
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
springfox-boot-starter What has been done ?
Swagger 3.0
One of the main features of the main push is the starter , So what does this starter do ?
「 Remember 」: All classes are automatically configured in the starter logic .
find springfox-boot-starter
Automatic configuration class of , stay /META-INF/spring.factories
In Archives , as follows :

As you can see from the picture above , Auto configuration class is OpenApiAutoConfiguration
, The original code is as follows :
@Configuration
@EnableConfigurationProperties(SpringfoxConfigurationProperties.class)
@ConditionalOnProperty(value = "springfox.documentation.enabled", havingValue = "true", matchIfMissing = true)
@Import({
OpenApiDocumentationConfiguration.class,
SpringDataRestConfiguration.class,
BeanValidatorPluginsConfiguration.class,
Swagger2DocumentationConfiguration.class,
SwaggerUiWebFluxConfiguration.class,
SwaggerUiWebMvcConfiguration.class
})
@AutoConfigureAfter({ WebMvcAutoConfiguration.class, JacksonAutoConfiguration.class,
HttpMessageConvertersAutoConfiguration.class, RepositoryRestMvcAutoConfiguration.class })
public class OpenApiAutoConfiguration {
}
Dare you, this automatic configuration class did nothing , Just import a few configuration classes (@Import
) And turn on property configuration (@EnableConfigurationProperties
).

「 Emphasis 」: Remember
OpenApiDocumentationConfiguration
This configuration class , At first glance, this is a BUG, I don't want to go into , The code in it is poorly written , No notes .
Rolling up your sleeves is dry ?
Seriously , It's the same as before , It's really not a big change , Follow the steps of the document step by step .
Customize a basic file example
Everything still needs to be configured manually , Seriously , I thought I would configure it in the global configuration file . Ah , I think too much. . The configuration classes are as follows :
@EnableOpenApi
@Configuration
@EnableConfigurationProperties(value = {SwaggerProperties.class})
public class SwaggerConfig {
/**
* Configuration properties
*/
@Autowired
private SwaggerProperties properties;
@Bean
public Docket frontApi() {
return new Docket(DocumentationType.OAS_30)
// Whether to open , Configuration according to environment
.enable(properties.getFront().getEnable())
.groupName(properties.getFront().getGroupName())
.apiInfo(frontApiInfo())
.select()
// Specify the package to scan
.apis(RequestHandlerSelectors.basePackage(properties.getFront().getBasePackage()))
.paths(PathSelectors.any())
.build();
}
/**
* Front desk API Information
*/
private ApiInfo frontApiInfo() {
return new ApiInfoBuilder()
.title(properties.getFront().getTitle())
.description(properties.getFront().getDescription())
.version(properties.getFront().getVersion())
.contact( // New developer information
new Contact(properties.getFront().getContactName(), properties.getFront().getContactUrl(),
properties.getFront().getContactEmail()))
.build();
}
}
@EnableOpenApi
The annotation file is explained as follows :
Indicates that Swagger support should be enabled.
This should be applied to a Spring java config and should have an accompanying '@Configuration' annotation.
Loads all required beans defined in @see SpringSwaggerConfig
What do you mean ? The general meaning is 「 Only the configuration class is marked with @EnableOpenApi
This annotation will generate Swagger file 」.
@EnableConfigurationProperties
This annotation enables custom property configuration to be enabled , This is the author's custom Swagger
To configure .
In short, the configuration is the same as before , According to official documents , You need to add a
@EnableOpenApi
Notes .
How files are grouped ?
We all know , A project may be divided into Front desk
, Backstage
,APP End
, Small program side
..... The interface on each end may still be the same , It's impossible to put them all together , It must be distinguished .
therefore , In actual development, files must be grouped .
Grouping is actually very simple ,Swagger
towards IOC
Put a Docket
This is a group file , One of them groupName()
Method to specify the name of the group .
So you just need to inject multiple Docket
Specify a different group name , Of course , The titles of these documents 、 describe 、 Scanning paths can be customized .
Two are configured as follows Docket
, It's divided into front desk and backstage , The configuration classes are as follows :
@EnableOpenApi
@Configuration
@EnableConfigurationProperties(value = {SwaggerProperties.class})
public class SwaggerConfig {
/**
* Configuration properties
*/
@Autowired
private SwaggerProperties properties;
@Bean
public Docket frontApi() {
return new Docket(DocumentationType.OAS_30)
// Whether to open , Configuration according to environment
.enable(properties.getFront().getEnable())
.groupName(properties.getFront().getGroupName())
.apiInfo(frontApiInfo())
.select()
// Specify the package to scan
.apis(RequestHandlerSelectors.basePackage(properties.getFront().getBasePackage()))
.paths(PathSelectors.any())
.build();
}
/**
* Front desk API Information
*/
private ApiInfo frontApiInfo() {
return new ApiInfoBuilder()
.title(properties.getFront().getTitle())
.description(properties.getFront().getDescription())
.version(properties.getFront().getVersion())
.contact( // New developer information
new Contact(properties.getFront().getContactName(), properties.getFront().getContactUrl(),
properties.getFront().getContactEmail()))
.build();
}
/**
* Backstage API
*/
@Bean
public Docket backApi() {
return new Docket(DocumentationType.OAS_30)
// Whether to open , Configuration according to environment
.enable(properties.getBack().getEnable())
.groupName(" Back office management ")
.apiInfo(backApiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage(properties.getBack().getBasePackage()))
.paths(PathSelectors.any())
.build();
}
/**
* Backstage API Information
*/
private ApiInfo backApiInfo() {
return new ApiInfoBuilder()
.title(properties.getBack().getTitle())
.description(properties.getBack().getDescription())
.version(properties.getBack().getVersion())
.contact( // New developer information
new Contact(properties.getBack().getContactName(), properties.getBack().getContactUrl(),
properties.getBack().getContactEmail()))
.build();
}
}
Attribute configuration file SwaggerProperties
as follows , It is divided into two different attribute configurations of foreground and background :
/**
* swagger Property configuration class for
*/
@ConfigurationProperties(prefix = "spring.swagger")
@Data
public class SwaggerProperties {
/**
* Foreground interface configuration
*/
private SwaggerEntity front;
/**
* Background interface configuration
*/
private SwaggerEntity back;
@Data
public static class SwaggerEntity {
private String groupName;
private String basePackage;
private String title;
private String description;
private String contactName;
private String contactEmail;
private String contactUrl;
private String version;
private Boolean enable;
}
}
Here is a screenshot of the file , You can see that there are two different groups :

How to add authorization information ?
Project now API There must be license authentication , Otherwise you can't access , For example, ask to carry a TOKEN
.
stay Swagger Authentication information can also be configured in , In this way, each request will be carried by default .
stay Docket
There are two ways to specify authorization information in , The difference is securitySchemes()
and securityContexts()
. The configuration in the configuration class is as follows , Building Docket When you set it in, you can :
@Bean
public Docket frontApi() {
RequestParameter parameter = new RequestParameterBuilder()
.name("platform")
.description(" Request head ")
.in(ParameterType.HEADER)
.required(true)
.build();
List<RequestParameter> parameters = Collections.singletonList(parameter);
return new Docket(DocumentationType.OAS_30)
// Whether to open , Configuration according to environment
.enable(properties.getFront().getEnable())
.groupName(properties.getFront().getGroupName())
.apiInfo(frontApiInfo())
.select()
// Specify the package to scan
.apis(RequestHandlerSelectors.basePackage(properties.getFront().getBasePackage()))
.paths(PathSelectors.any())
.build()
.securitySchemes(securitySchemes())
.securityContexts(securityContexts());
}
/**
* Set authorization information
*/
private List<SecurityScheme> securitySchemes() {
ApiKey apiKey = new ApiKey("BASE_TOKEN", "token", In.HEADER.toValue());
return Collections.singletonList(apiKey);
}
/**
* Global application of authorization information
*/
private List<SecurityContext> securityContexts() {
return Collections.singletonList(
SecurityContext.builder()
.securityReferences(Collections.singletonList(new SecurityReference("BASE_TOKEN", new AuthorizationScope[]{new AuthorizationScope("global", "")})))
.build()
);
}
After the above configuration is successful , stay Swagger There will be Authorize
Button , Just add in the request header . Here's the picture :

How to carry public request arguments ?
Different architectures may send requests in addition to carrying TOKEN
, It also carries different arguments , For example, the requested platform , Version, etc. , The arguments that each request carries are called public arguments .
So how is Swagger
How about the public arguments defined in ? For example, carry in the request header .
stay Docket
The method in globalRequestParameters()
Public request arguments can be set , The received argument is a List<RequestParameter>
, So just build one RequestParameter
Assemble , as follows :
@Bean
public Docket frontApi() {
// Construct a public request argument platform, Put in header
RequestParameter parameter = new RequestParameterBuilder()
// Argument name
.name("platform")
// describe
.description(" Requested platform ")
// Put it in header in
.in(ParameterType.HEADER)
// Is it necessary
.required(true)
.build();
// Build a set of request arguments
List<RequestParameter> parameters = Collections.singletonList(parameter);
return new Docket(DocumentationType.OAS_30)
.....
.build()
.globalRequestParameters(parameters);
}
The above configuration is complete , You will see a request header in each interface , Here's the picture :

It's a rough one BUG
When the author introduces the automatic configuration class, he mentioned , Now let's make a brief analysis of .
OpenApiAutoConfiguration
This autoconfiguration class has already imported OpenApiDocumentationConfiguration
This configuration class , The following code :
@Import({
OpenApiDocumentationConfiguration.class,
......
})
@EnableOpenApi
The original code of is as follows :
@Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME)
@Target(value = {java.lang.annotation.ElementType.TYPE})
@Documented
@Import(OpenApiDocumentationConfiguration.class)
public @interface EnableOpenApi {
}
You can see from the original code that :@EnableOpenApi
The function of this annotation is to import OpenApiDocumentationConfiguration
This configuration class , Nani ???
Now that you're already configuring classes automatically OpenApiAutoConfiguration
It's in , Then, whether you need to label the configuration class or not @EnableOpenApi
Annotations don't always open Swagger
Support ?
「 Test it 」: Do not label on configuration class @EnableOpenApi
This note , See if Swagger
Perform normally . The results were expected , It can still be executed normally .
「 Summary 」: The author only makes a general analysis of , This could be a
BUG
Or there are other purposes to follow , So it turns out , I don't want to verify it , It doesn't mean anything .
Summary
This article is also a taste of fresh , I don't feel very fragrant , A little disappointed . Do you like it? ?
Spring Boot
The integrated source code has been uploaded , Need friend public name reply key words 「Swagger3.0」 Get . Click to go
版权声明
本文为[itread01]所创,转载请带上原文链接,感谢
边栏推荐
- Solve the problem of database insert data garbled in PL / SQL developer
- DC-1靶機
- With the advent of tensorflow 2.0, can pytoch still shake the status of big brother?
- [Xinge education] poor learning host computer series -- building step 7 Simulation Environment
- StickEngine-架构11-消息队列(MessageQueue)
- Shh! Is this really good for asynchronous events?
- (1) ASP.NET Introduction to core3.1 Ocelot
- 一篇文章带你了解CSS3 背景知识
- How to get started with new HTML5 (2)
- 游戏开发中的新手引导与事件管理系统
猜你喜欢
【字节跳动 秋招岗位开放啦】Ohayoo!放学别走,我想约你做游戏!!!
只有1个字节的文件实际占用多少磁盘空间
快速排序为什么这么快?
这个项目可以让你在几分钟快速了解某个编程语言
GUI engine evaluation index
Live broadcast preview | micro service architecture Learning Series live broadcast phase 3
【自学unity2d传奇游戏开发】如何让角色动起来
How to turn data into assets? Attracting data scientists
What are PLC Analog input and digital input
The AI method put forward by China has more and more influence. Tianda et al. Mined the development law of AI from a large number of literatures
随机推荐
The data of pandas was scrambled and the training machine and testing machine set were selected
Our best practices for writing react components
Solve the problem of database insert data garbled in PL / SQL developer
Five vuex plug-ins for your next vuejs project
代码生成器插件与Creator预制体文件解析
Details of dapr implementing distributed stateful service
Music generation through deep neural network
How to get started with new HTML5 (2)
只有1个字节的文件实际占用多少磁盘空间
Elasticsearch Part 6: aggregate statistical query
Humor: hacker programming is actually similar to machine learning!
用一个例子理解JS函数的底层处理机制
【自学unity2d传奇游戏开发】地图编辑器
Pattern matching: The gestalt approach一种序列的文本相似度方法
有了这个神器,快速告别垃圾短信邮件
事务的隔离级别与所带来的问题
零基础打造一款属于自己的网页搜索引擎
Construction of encoder decoder model with keras LSTM
快速排序为什么这么快?
React design pattern: in depth understanding of react & Redux principle