Swagger generate JavaDoc
In their daily work, especially now under the front and rear ends of the separation modes, to provide an interface caused us to communicate before and after the end of the developers of
significant cost increase, because communication is not in place, not timely caused [tear currency] events have become daily work. In particular, many developers
are not good at communication, the result will make its own particular pain, but also to co-workers 恨
root itch.
In order to end the war spread, and in order to improve customer satisfaction developers, Swagger
came into being.
What is Swagger
Swagger for Everyone
Simplify API development for users, teams, and enterprises with the Swagger open source and professional toolset.
Swagger open source and pro tools have helped millions of API developers, teams, and organizations deliver great APIs.
In short, it refers to the use set of tools to simplify user, team and API development companies.
- The official portal
- Source Portal
- Swagger-UI Portal
- Expanding component swagger-spring-boot-starter portal
- Extended UI components swagger-bootstrap-ui portal
Integrated Swagger
I chose to use the system is swagger-spring-boot-starter
.
To achieve rapid introduction of the swagger2 spring boot application to generate API documentation, simplify native use swagger2 The project of integration code using automated configuration features of Spring Boot.
See, I teach everyone to use are lazy Oh, it's not a good sign. . .
Add dependent
<!--整合Swagger2-->
<dependency>
<groupId>com.spring4all</groupId>
<artifactId>swagger-spring-boot-starter</artifactId>
<version>1.9.0.RELEASE</version>
</dependency>
Click the version number to enter swagger-spring-boot-starter/1.9.0.RELEASE/swagger-spring-boot-starter-1.9.0.RELEASE.pom
, you can see the version information which it depends.
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<version.java>1.8</version.java>
<version.swagger>2.9.2</version.swagger>
<version.spring-boot>1.5.10.RELEASE</version.spring-boot>
<version.lombok>1.18.6</version.lombok>
</properties>
Enable function
In our class started ApiApplication
to increase on the annotation @ EnableSwagger2Doc
@SpringBootApplication
@MapperScan(basePackages = "com.liferunner.mapper")
@ComponentScan(basePackages = {"com.liferunner", "org.n3r.idworker"})
@EnableSwagger2Doc //启动Swagger
public class ApiApplication {
public static void main(String[] args) {
new SpringApplicationBuilder()
.sources(ApiApplication.class)
.run(args);
}
@Autowired
private CORSConfig corsConfig;
/**
* 注册跨域配置信息
*
* @return {@link CorsFilter}
*/
@Bean
public CorsFilter corsFilter() {
val corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin(this.corsConfig.getAllowOrigin());
corsConfiguration.addAllowedMethod(this.corsConfig.getAllowedMethod());
corsConfiguration.addAllowedHeader(this.corsConfig.getAllowedHeader());
corsConfiguration.setAllowCredentials(this.corsConfig.getAllowCredentials());
val urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(urlBasedCorsConfigurationSource);
}
}
Configuring basic information
Through properties
files and yml/yaml
configuration files.
# 配置swagger2
swagger:
enabled: true #是否启用swagger,默认:true
title: 实战电商api平台
description: provide 电商 API
version: 1.0.0.RC
license: Apache License, Version 2.0
license-url: https://www.apache.org/licenses/LICENSE-2.0.html
terms-of-service-url: http://www.life-runner.com
contact:
email: [email protected]
name: Isaac-Zhang
url: http://www.life-runner.com
base-package: com.liferunner
base-path: /**
A stage effect
Api run our projects, enter in your browser: http://localhost:8088/swagger-ui.html
you can see the following:
you can see, we have yml
information on the configuration file, displayed in the top of the page, click on 用户管理
:
From the chart we can see, our /users/create
interface to display out, and to the incoming parameters, the request type and so forth have been demonstrated in the figure above.
However, the parameters of what it means to be passed, are our field information, how do we make it more friendly to show it to the caller? Let us continue
to improve our document information:
Complete description Information
When we create a user, you need to pass an com.liferunner.dto.UserRequestDTO
object properties of this object are as follows:
@RestController
@RequestMapping(value = "/users")
@Slf4j
@Api(tags = "用户管理")
public class UserController {
@Autowired
private IUserService userService;
@ApiOperation(value = "用户详情", notes = "查询用户")
@ApiIgnore
@GetMapping("/get/{id}")
//@GetMapping("/{id}") 如果这里设置位这样,每次请求swagger都会进到这里,是一个bug
public String getUser(@PathVariable Integer id) {
return "hello, life.";
}
@ApiOperation(value = "创建用户", notes = "用户注册接口")
@PostMapping("/create")
public JsonResponse createUser(@RequestBody UserRequestDTO userRequestDTO) {
//...
}
}
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@ApiModel(value = "创建用户DTO", description = "用户注册需要的参数对象")
public class UserRequestDTO {
@ApiModelProperty(value = "用户名", notes = "username", example = "isaaczhang", required = true)
private String username;
@ApiModelProperty(value = "注册密码", notes = "password", example = "12345678", required = true)
private String password;
@ApiModelProperty(value = "确认密码", notes = "confimPassword", example = "12345678", required = true)
private String confirmPassword;
}
We can see, we have a lot through @Apixxx
the beginning of the explanatory notes, this is the Swagger available to us to illustrate the notes and documentation of field.
@Api
Represent provide external API@ApiIgnore
Means no external display, it can be used for classes and methods@ApiOperation
The API refers to one of the following actions CURD@ApiResponses
Exceptions described operation may occur@ApiParam
Describes a single pass parameter information@ApiModel
Java object is used to describe the properties described@ApiModelProperty
Description object field descriptions
for all to use, can enter comments related to the specific class to see all of the attribute information, are relatively simple, here it does not specifically described. Want to see more properties instructions,
you can enter: Swagger Property Description Portal .
After configuring, restart the application, UI refresh the page:
image above the red line delineated description of the information we are reconfigured, it is simple enough -
Integrated UI interface better with the
For in the API, the above information we have good enough, but do technology, we should pursue a more extreme point of the UI interface we provide large quantities
' s user interface, so there is a friendly Diudiu lack, and now for everyone to re-introduce a better use of open source Swagger UI
, there is please Swagger-Bootstrap-ui .
We can see from the chart, the number of UI Star has more than 1.1K, and this proves that it has been very good, and we are going to unlock its true colors now.
Integrated dependence
We only need to expensive-shop\pom.xml
rely on the code by adding the following:
<!--一种新的swagger ui-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.6</version>
</dependency>
Preview
After adding a dependency, we just need to restart the application, and then access the http://localhost:8088/doc.html
effect is as follows:
Click Create User:
the above effect is not more in line with our aesthetic of the ~
So far, we used Swagger
to dynamically generate API demonstration effect has been all over but if one day we can not connect to a time and check out our website customers to integrate, how do we do it?
Or to a handwritten document to them? That we do not do it as a very painful! ! !
As a programmer, we absolutely can not allow this to happen!
Let us read on.
Offline document generation
In order to let us do the painful work, we now have added so much descriptive information in the code, if there is a way you can help us to generate an offline document it? The answer is yes.
Open source projects swagger2markup
A Swagger to AsciiDoc or Markdown converter to simplify the generation of an up-to-date RESTful API documentation by combining documentation that’s been hand-written with auto-generated API documentation.
Source Portal
documents Portal
Swagger2Markup it is mainly used to convert Swagger automatically generated document into several popular formats to offline
formats: AsciiDoc, HTML, Markdown, Confluence
MAVEN document using the plug-in generates AsciiDoc
In mscx-shop-api\pom.xml
dependence adding the following code:
<build>
<plugins>
<!--生成 AsciiDoc 文档(swagger2markup)-->
<plugin>
<groupId>io.github.swagger2markup</groupId>
<artifactId>swagger2markup-maven-plugin</artifactId>
<version>1.3.3</version>
<configuration>
<!--这里是要启动我们的项目,然后抓取api-docs的返回结果-->
<swaggerInput>http://localhost:8088/v2/api-docs</swaggerInput>
<outputDir>src/docs/asciidoc/generated-doc</outputDir>
<config>
<swagger2markup.markupLanguage>ASCIIDOC</swagger2markup.markupLanguage>
</config>
</configuration>
</plugin>
</plugins>
</build>
<swaggerInput>http://localhost:8088/v2/api-docs</swaggerInput>
In order to obtain ourapi JSON
data, as shown below:
<outputDir>src/docs/asciidoc/generated-doc</outputDir>
We want to set the directory address generated
Excuting an order:
expensive-shop\mscx-shop-api>mvn swagger2markup:convertSwagger2markup
If you think the command is too long, you can click IDEA => Maven => mscx-shop-api => Plugins => swagger2markup => swagger2markup:convertSwagger2markup
on it to perform it, as shown below:
generating the following results:
the ADoC file generated good, then we use it to generate html it
MAVEN use plug-in generates HTML
In mscx-shop-api\pom.xml
dependence adding the following code:
<!--生成 HTML 文档-->
<plugin>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctor-maven-plugin</artifactId>
<version>1.5.6</version>
<configuration>
<sourceDirectory>src/docs/asciidoc/generated-doc</sourceDirectory>
<outputDirectory>src/docs/asciidoc/html</outputDirectory>
<backend>html</backend>
<sourceHighlighter>coderay</sourceHighlighter>
<attributes>
<toc>left</toc>
</attributes>
</configuration>
</plugin>
<sourceDirectory>src/docs/asciidoc/generated-doc</sourceDirectory>
Source files directory as we generated on a adoc<outputDirectory>src/docs/asciidoc/html</outputDirectory>
Specify the output directory
Execute commands generated:
\expensive-shop\mscx-shop-api>mvn asciidoctor:process-asciidoc
Generating results were as follows:
open overview.html
, as follows:
At this point, we will have all the documentation generated!
Notice under section
The next section we will continue to develop our home page to show users log on and some information to use in the course of any development component, I will be a special presentation by one of the brothers late panic!
gogogo!