= My Document's Title Doc Writer <doc.writer@asciidoctor.org> v1.0, 2018-04-11 :toc: :imagesdir: assets/images :homepage: https://asciidoctor.org My document provides...
= 文檔標題 (0級) = == 段落標題 (1級) == === 段落標題 (2級) === ==== 段落標題 (3級) ==== ===== 段落標題 (4級) =====
Paragraphs don’t require any special markup in AsciiDoc. A paragraph is just one or more lines of consecutive text. To begin a new paragraph, separate it by at least one blank line. Newlines within a paragraph are not displayed.
Rubies are red, + Topazes are blue. [%hardbreaks] Ruby is red. Java is black.
:hardbreaks: ...... Rubies are red, Topazes are blue.
標簽說明 NOTE 注釋,TIP 提示,WARNING 警告,IMPORTANT 重要,CAUTION 注意。
TIP: Pro tip... IMPORTANT: Don't forget... WARNING: Watch out for... CAUTION: Ensure that...
[IMPORTANT] .Feeding the Werewolves ==== While werewolves are hardy community members, keep in mind the following dietary concerns: . They are allergic to cinnamon. . More than two glasses of orange juice in 24 hours makes them howl in harmony with alarms and sirens. . Celery makes them sad. ====
[icons="./images/icons/wink.png"] NOTE: What lovely war.
[icons=None, caption="特殊提示"] NOTE: This is my special note.
= Document Title :icons: font ...... NOTE: Asciidoctor supports font-based admonition icons, powered by Font Awesome!
<div class="admonitionblock note"> <table> <tr> <td class="icon"> <i class="fa icon-note" title="Note"></i> </td> <td class="content"> Asciidoctor supports font-based admonition icons, powered by Font Awesome! </td> </tr> </table> </div>
<link rel="stylesheet" >
:tip-caption: [TIP] It's possible to use Unicode glyphs as admonition icons.
<td class="icon"> <div class="title"></div> </td>
icon:tags[] ruby, asciidoctor
<div class="paragraph"> <p><span class="icon"><i class="fa fa-tags"></i></span> ruby, asciidoctor</p> </div>
icon:tags[role="blue"] ruby, asciidoctor
icon:heart[2x] icon:heart[size=2x]
icon:shield[rotate=90, flip=vertical]
icon:download[link="http://rubygems.org/downloads/asciidoctor-1.5.2.gem"]
[.lead] This text will be styled as a lead paragraph (i.e., larger font).
error: The requested operation returned error: 1954 Forbidden search for defensive operations manual absolutely fatal: operation initiation lost in the dodecahedron of doom would you like to die again? y/n .... Lazarus: Where is the *defensive operations manual*? Computer: Calculating ... Can not locate object that you are not authorized to know exists. Would you like to ask another question? Lazarus: Did the werewolves tell you to say that? Computer: Calculating ... ....
注意:在輸出中,粗體文本格式沒有應用于文本。
[literal] error: The requested operation returned error: 1954 Forbidden search for defensive operations manual absolutely fatal: operation initiation lost in the dodecahedron of doom would you like to die again? y/n
// A single-line comment.
//// CommentBlock ////
[listing] This is an example of a paragraph styled with `listing`. Notice that the monospace markup is preserved in the output.
.app.rb [source,ruby] ---- require 'sinatra' get '/hi' do "Hello World!" end
:version: 1.5.6.1 [source,xml,subs="verbatim,attributes"] ---- <dependency> <groupId>org.asciidoctor</groupId> <artifactId>asciidoctor-java-integration</artifactId> <version>{version}</version> </dependency> ----
[source%nowrap,java] ---- public class ApplicationConfigurationProvider extends HttpConfigurationProvider { @Override public Configuration getConfiguration(ServletContext context) { return ConfigurationBuilder.begin() .addRule() .when(Direction.isInbound().and(Path.matches("/{path}"))) .perform(Log.message(Level.INFO, "Client requested path: {path}")) .where("path").matches(".*"); } } ----
:prewrap!:
.Gemfile.lock ---- GEM remote: https://rubygems.org/ specs: asciidoctor (1.5.6.1) PLATFORMS ruby DEPENDENCIES asciidoctor (~> 1.5.6.1) ----
[source,ruby] ---- require 'sinatra' // <1> get '/hi' do // <2> "Hello World!" // <3> end ---- <1> Library import <2> URL mapping <3> HTTP response body
---- line of code // <1> line of code # <2> line of code ;; <3> ---- <1> A callout behind a line comment for C-style languages. <2> A callout behind a line comment for Ruby, Python, Perl, etc. <3> A callout behind a line comment for Clojure.
[source,xml] ---- <section> <title>Section Title</title> <!--1--> </section> ---- <1> The section title is required.
[source,ruby] ---- include::app.rb[] ----
:sourcedir: src/main/java [source,java] ---- include::{sourcedir}/org/asciidoctor/Asciidoctor.java[] ----
[source,ruby,indent=0] ---- include::lib/document.rb[lines=5..10] ----
[source,xml] <meta name="viewport" content="width=device-width, initial-scale=1.0"> This is normal content.
:source-highlighter: pygments
.AsciiDoc history **** AsciiDoc was first released in Nov 2002 by Stuart Rackham. It was designed from the start to be a shorthand syntax for producing professional documents like DocBook and LaTeX. ****
____ QuoteBlock ____
[quote, Abraham Lincoln, Address delivered at the dedication of the Cemetery at Gettysburg] ____ Four score and seven years ago our fathers brought forth on this continent a new nation... ____ [quote, Albert Einstein] A person who never made a mistake never tried anything new. ____ A person who never made a mistake never tried anything new. ____ [quote, Charles Lutwidge Dodgson, 'Mathematician and author, also known as http://en.wikipedia.org/wiki/Lewis_Carroll[Lewis Carroll]'] ____ If you don't know where you are going, any road will get you there. ____
"I hold it that a little rebellion now and then is a good thing, and as necessary in the political world as storms in the physical." -- Thomas Jefferson, Papers of Thomas Jefferson: Volume 11
[, James Baldwin] "" Not everything that is faced can be changed. But nothing can be changed until it is faced. ""
==== ExampleBlock ====
.Sample document ==== Here's a sample AsciiDoc document: [listing] .... = Title of Document Doc Writer :toc: This guide provides... .... The document header is useful, but not required. ==== [NOTE] ==== An admonition block may contain complex content. .A list - one - two - three Another paragraph. ====
-- An open block can be an anonymous container, or it can masquerade as any other block. -- [source] -- puts "I'm a source block!" --
1. 阿拉伯數字標注的列表項目. a. 小寫字母標注的列表項目. F. 大寫字母標注的列表項目. iii) 小寫羅馬數字標注的列表項目. IX) 大寫羅馬數字標注的列表項目.
- List item. * List item. ** List item. *** List item. **** List item. ***** List item.
Operating Systems:: Linux::: . Fedora * Desktop . Ubuntu * Desktop * Server BSD::: . FreeBSD . NetBSD Cloud Providers:: PaaS::: . OpenShift . CloudBees IaaS::: . Amazon EC2 . Rackspace
[qanda] What is Asciidoctor?:: An implementation of the AsciiDoc processor in Ruby. What is the answer to the Ultimate Question?:: 42
* [*] checked * [x] also checked * [ ] not checked * normal list item
first term:: definition of first term second term:: definition of second term
first term:: definition of first term second term:: definition of second term
[glossary] 術語1:: 解釋1. 術語2:: 解釋2.
*bold phrase* & **char**acter**s**
_italic phrase_ & __char__acter__s__
`monospace phrase` & ``char``acter``s``
You can reference the value of a document attribute using the syntax `+{name}+`, where `name` is the attribute name.
`*_monospace bold italic phrase_*` & ``**__char__**``acter``**__s__**``
Werewolves are allergic to #cassia cinnamon#.
Did the werewolves read the [.small]##small print##?
[.big]##O##nce upon an infinite loop.
We need [.line-through]#ten# make that twenty VMs.
Where did all the [.underline]#cores# run off to?
^super^script phrase
~sub~script phrase
"`double curved quotes`" '`single curved quotes`' Olaf's desk was a mess. All of the werewolves`' desks were a mess. Olaf had been with the company since the `'60s. “double curved quotes” ‘single curved quotes’ Olaf’s desk was a mess. All of the werewolves’ desks were a mess. Olaf had been with the company since the ’60s.
符號顯示說明(C)?版權(TM)?商標(R)?注冊商標…?...省略號->→右箭頭<-←左箭頭=>?右雙箭頭<=?左雙箭頭??數字--—破折號(只能在兩個字符之間使用)
hhhh;
= Reference Documentation Lead Developer This is documentation for project X. include::basics.adoc[] include::installation.adoc[] include::example.adoc[]
include::https://raw.githubusercontent.com/asciidoctor/asciidoctor/master/README.adoc[]
'''
<<<
https://asciidoctor.org - automatic! https://asciidoctor.org[Asciidoctor] https://github.com/asciidoctor[Asciidoctor @ *GitHub*]
link:++https://example.org/?q=[a b]++[URL with special characters] link:https://example.org/?q=%5Ba%20b%5D[URL with special characters]
link:\\server\share\whitepaper.pdf[Whitepaper]
link:index.html[Docs]
devel@discuss.arquillian.org mailto:devel@discuss.arquillian.org[Discuss Arquillian] mailto:devel-join@discuss.arquillian.org[Subscribe, Subscribe me, I want to join!] irc://irc.freenode.org/#fedora
錨點:[[A88]] 鏈接:<<A88,chapter titles>>
image::sunset.jpg[] image::sunset.jpg[Sunset] .A mountain sunset [#img-sunset] [caption="Figure 1: ",link=https://www.flickr.com/photos/javh/5448336655] image::sunset.jpg[Sunset,300,200] image::https://asciidoctor.org/images/octocat.jpg[GitHub mascot]
Click image:icons/play.png[Play, title="Play"] to get the party started. Click image:icons/pause.png[title="Pause"] when you need a break.
image:sunset.jpg[Sunset,150,150,role="right"] What a beautiful sunset!
video::video_file.mp4[] video::video_file.mp4[width=640, start=60, end=140, options=autoplay]
Reference code like `types` or `methods` inline.
Output literal monospace text such as `+{backtick}+` by enclosing the text in pluses, then again in backticks.
= AsciiDoc Writer's Guide Doc Writer <doc.writer@asciidoctor.org> v1.0, 2013-08-01 :toc: right
_The Pragmatic Programmer_ <<pp>> should be required reading for all developers. To learn all about design patterns, refer to the book by the "`Gang of Four`" <<gof>>. [bibliography] == References - [[[pp]]] Andy Hunt & Dave Thomas. The Pragmatic Programmer: From Journeyman to Master. Addison-Wesley. 1999. - [[[gof,2]]] Erich Gamma, Richard Helm, Ralph Johnson & John Vlissides. Design Patterns: Elements of Reusable Object-Oriented Software. Addison-Wesley. 1994.
A statement.footnote:[Clarification about this statement.] A bold statement!footnoteref:[disclaimer,Opinions are my own.] Another bold statement.footnoteref:[disclaimer]
.Table Title |=== |Name of Column 1 |Name of Column 2 |Name of Column 3 |Cell in column 1, row 1 |Cell in column 2, row 1 |Cell in column 3, row 1 |Cell in column 1, row 2 |Cell in column 2, row 2 |Cell in column 3, row 2 |===
[%header,cols=2*] |=== |Name of Column 1 |Name of Column 2 |Cell in column 1, row 1 |Cell in column 2, row 1 |Cell in column 1, row 2 |Cell in column 2, row 2 |===
[cols="1,1,2", options="header"] .Applications |=== |Name |Category |Description |Firefox |Browser |Mozilla Firefox is an open-source web browser. It's designed for standards compliance, performance, portability. |Arquillian |Testing |An innovative and highly extensible testing platform. Empowers developers to easily create real, automated tests. |===
[cols="2,2,5a"] |=== |Firefox |Browser |Mozilla Firefox is an open-source web browser. It's designed for: * standards compliance * performance * portability http://getfirefox.com[Get Firefox]! |===
[%header,format=csv] |=== Artist,Track,Genre Baauer,Harlem Shake,Hip Hop The Lumineers,Ho Hey,Folk Rock |===
,=== Artist,Track,Genre Baauer,Harlem Shake,Hip Hop ,===
|=== include::customers.csv[] |===
:=== Artist:Track:Genre Robyn:Indestructable:Dance :===
[cols="e,m,^,>s", width="25%"] |=== |1 >s|2 |3 |4 ^|5 2.2+^.^|6 .3+<.>m|7 ^|8 |9 2+>|10 |===
:url-home: https://asciidoctor.org :link-docs: https://asciidoctor.org/docs[documentation] :summary: Asciidoctor is a mature, plain-text document format for \ writing notes, articles, documentation, books, and more. \ It's also a text processor & toolchain for translating \ documents into various output formats (i.e., backends), \ including HTML, DocBook, PDF and ePub. :checkedbox: pass:normal[{startsb}?{endsb}] Check out {url-home}[Asciidoctor]! {summary} Be sure to read the {link-docs} too! {checkedbox} That's done!
[caption=""] .Parts{counter2:index:0} |=== |Part Id |Description |PX-{counter:index} |Description of PX-{index} |PX-{counter:index} |Description of PX-{index} |===
\*Stars* is not rendered as bold text. The asterisks around the word are preserved. \{author} is not resolved to the author name. The curly brackets around the word are preserved. `A\--Z` connects A to Z in monospace using two dashes. The dashes are not replaced by an em dash. \[[Word]] is not interpreted as an anchor. The double brackets around the word are preserved. [\[[Word]]] is not interpreted as a bibliography anchor. The triple brackets around the word are preserved. In these cases, the backslash character is automatically removed.
`+Text inside {plus} characters+` is not formatted. However, special characters like +<+ and +>+ are still escaped.
pass:[<u>underline me</u>] is also underlined.
+++<u>underline me</u>+++ is underlined.
# Document Title (Level 0) ## Section Level 1 ### Section Level 2 #### Section Level 3 ##### Section Level 4 ###### Section Level 5
```ruby require 'sinatra' get '/hi' do "Hello World!" end \``` \\ 去除第一個 \ 符號
> I hold it that a little rebellion now and then is a good thing, > and as necessary in the political world as storms in the physical. > -- Thomas Jefferson, Papers of Thomas Jefferson: Volume 11
> > What's new? > > I've got Markdown in my AsciiDoc! > > > Like what? > > * Blockquotes > * Headings > * Fenced code blocks > > > Is there more? > > Yep. AsciiDoc and Markdown share a lot of common syntax already.
--- - - - *** * * *
https://asciidoctor.org/docs/
近經常被問 https://t.itmuch.com/doc.html 文檔頁是怎么制作的,考慮到步驟略復雜,寫篇手記總結下吧。
TIPS
https://t.itmuch.com/doc.html 是個人在慕課網視頻《 面向未來微服務:Spring Cloud Alibaba從入門到進階[1] 》的實戰項目配套文檔。
?整合Swagger,生成Swagger描述端點 /v2/api-docs
?使用 swagger2markup-maven-plugin ,將 /v2/api-docs 生成ASCIIDOC文件;
?使用 asciidoctor-maven-plugin ,將ASCIIDOC文件轉換成HTML;
?部署
TIPS
Swagger的使用非常簡單,本文不展開探討了,各位看官自行百度一下用法吧。
常用注解:
?@Api
?@ApiOperation
?@ApiModel
?@ApiModelProperty
1 加依賴
<!-- swagger --> <!-- 之所以要排除,是因為如果不排除會報NumberFormatException的警告。 --> <!-- 參考:https://github.com/springfox/springfox/issues/2265--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> <exclusions> <exclusion> <groupId>io.swagger</groupId> <artifactId>swagger-annotations</artifactId> </exclusion> <exclusion> <groupId>io.swagger</groupId> <artifactId>swagger-models</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.swagger</groupId> <artifactId>swagger-annotations</artifactId> <version>1.5.21</version> </dependency> <dependency> <groupId>io.swagger</groupId> <artifactId>swagger-models</artifactId> <version>1.5.21</version> </dependency>
2 配置Swagger(按照自己的需要配置,下面的配置代碼僅供參考)
/** * @author itmuch.com */ @Configuration @EnableSwagger2 public class SwaggerConfiguration { /** * swagger 信息 * * @return 頁面信息 */ private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("ITMuch API") .description("ITMuch API") .termsOfServiceUrl("") .version("1.0.0") .contact(new Contact("", "", "")).build(); } @Bean public Docket customImplementation() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.itmuch")) .paths(PathSelectors.any()) .build() .apiInfo(this.apiInfo()); //.globalOperationParameters(parameters); } }
3 為接口Swagger注解
@RestController @RequestMapping("/notices") @RequiredArgsConstructor(onConstructor = @__(@Autowired)) @Api(tags = "公告相關接口", description = "公告相關接口") public class NoticeController { /** * 查詢最新的一條公告 * * @return 公告列表 */ @GetMapping("/newest") @ApiOperation(value = "查詢最新的一條公告", notes = "用于:公告") public Notice findNewest() { return new Notice(); } } @AllArgsConstructor @NoArgsConstructor @Builder @Data @ApiModel("公告") public class Notice { /** * ID */ @ApiModelProperty("id") private Integer id; /** * 公告內容 */ @ApiModelProperty("公告內容") private String content; ... }
這樣,應用啟動完成后,就會有一個/v2/api-docs 端點,描述了你的API的信息。
在pom.xml中添加如下內容:
<build> <plugins> <plugin> <groupId>io.github.swagger2markup</groupId> <artifactId>swagger2markup-maven-plugin</artifactId> <version>1.3.1</version> <configuration> <!-- api-docs訪問url --> <swaggerInput>http://localhost:8080/v2/api-docs</swaggerInput> <!-- 生成為單個文檔,輸出路徑 --> <outputFile>src/docs/asciidoc/generated/all</outputFile> <config> <!-- ascii格式文檔 --> <swagger2markup.markupLanguage>ASCIIDOC</swagger2markup.markupLanguage> <swagger2markup.pathsGroupedBy>TAGS</swagger2markup.pathsGroupedBy> </config> </configuration> </plugin> ...
swagger2markup-maven-plugin 插件的作用是讀取 http://localhost:8080/v2/api-docs 的信息,生成ASCIIDOC文檔。當然你也可以生成其他格式,比如Markdown等等。
這款插件還有很多使用姿勢,詳見 https://github.com/Swagger2Markup/swagger2markup-maven-plugin[2]
下面,只需要將ASCIIDOC轉換成html就OK了,在pom.xml中添加如下內容:
<build> <plugins> <plugin> <groupId>org.asciidoctor</groupId> <artifactId>asciidoctor-maven-plugin</artifactId> <version>1.5.6</version> <configuration> <!-- asciidoc文檔輸入路徑 --> <sourceDirectory>src/docs/asciidoc/generated</sourceDirectory> <!-- html文檔輸出路徑 --> <outputDirectory>src/docs/asciidoc/html</outputDirectory> <backend>html</backend> <sourceHighlighter>coderay</sourceHighlighter> <!-- html文檔格式參數 --> <attributes> <doctype>book</doctype> <toc>left</toc> <toclevels>3</toclevels> <numbered></numbered> <hardbreaks></hardbreaks> <sectlinks></sectlinks> <sectanchors></sectanchors> </attributes> </configuration> </plugin>
asciidoctor-maven-plugin 插件同樣也有很多姿勢,詳見:https://github.com/asciidoctor/asciidoctor-maven-plugin[3]
生成的文件在 src/docs/asciidoc/html (看你插件上面的配置哈),然后你就可以弄個NGINX部署了。
最近將個人學習筆記整理成冊,使用PDF分享。關注我,回復如下代碼,即可獲得百度盤地址,無套路領取!
?001:《Java并發與高并發解決方案》學習筆記;
?002:《深入JVM內核——原理、診斷與優化》學習筆記;
?003:《Java面試寶典》
?004:《Docker開源書》
?005:《Kubernetes開源書》
?006:《DDD速成(領域驅動設計速成)》
[1] 面向未來微服務:Spring Cloud Alibaba從入門到進階: https://coding.imooc.com/class/358.html
[2]: https://github.com/Swagger2Markup/swagger2markup-maven-plugin
[3]: https://github.com/asciidoctor/asciidoctor-maven-plugin
相信很多后端開發在項目中都會碰到要寫 api 文檔,不管是給前端、移動端等提供更好的對接,還是以后為了以后交接方便,都會要求寫 api 文檔。
而手寫 api 文檔的話有諸多痛點:
Swagger 就很好地解決了這個問題。
Swagger 是一個規范和完整的框架,用于生成、描述、調用和可視化 RESTful 風格的 Web 服務。總體目標是使客戶端和文件系統作為服務器以同樣的速度來更新。文件的方法,參數和模型緊密集成到服務器端的代碼,允許API來始終保持同步。
<!--swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket buildDocket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(buildApiInf()) //將api的元信息設置為包含在json resourcelisting響應中
//.host("127.0.0.1:8080") //設置ip和端口,或者域名
.select() //啟動用于api選擇的生成器
//.apis(RequestHandlerSelectors.any())
.apis(RequestHandlerSelectors.basePackage("cn.zwqh.springboot.controller"))//指定controller路徑
.paths(PathSelectors.any()).build();
}
private ApiInfo buildApiInf() {
Contact contact=new Contact("朝霧輕寒","https://www.zwqh.top/","zwqh@clover1314.com");
return new ApiInfoBuilder()
.title("Swagger Demo Restful API Docs")//文檔標題
.description("Swagger 示例 Restful Api 文檔")//文檔描述
.contact(contact)//聯系人
.version("1.0")//版本號
//.license("")//更新此API的許可證信息
//.licenseUrl("")//更新此API的許可證Url
//.termsOfServiceUrl("")//更新服務條款URL
.build();
}
}
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
/**
* 靜態資源配置(默認)
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");// 靜態資源路徑
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
super.addResourceHandlers(registry);
}
}
如果不添加此靜態資源配置會報錯,找不到相關路徑
@ApiModel(value = "UserEntity", description = "用戶對象")
public class UserEntity implements Serializable{
/**
*
*/
private static final long serialVersionUID = 5237730257103305078L;
@ApiModelProperty(value ="用戶id",name="id",dataType="Long",required = false,example = "1",hidden = false )
private Long id;
@ApiModelProperty(value ="用戶名",name="userName",dataType="String",required = false,example = "關羽" )
private String userName;
@ApiModelProperty(value ="用戶性別",name="userSex",dataType="String",required = false,example = "男" )
private String userSex;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserSex() {
return userSex;
}
public void setUserSex(String userSex) {
this.userSex = userSex;
}
}
@RestController
@RequestMapping("/api")
@Api(tags = { "接口分組1", "接口分組2" })
public class ApiController {
@Autowired
private UserDao userDao;
@GetMapping("/getAllUser")
@ApiOperation(value = "獲取所有用戶", notes = "", httpMethod = "GET", tags = "接口分組3")
public List<UserEntity> getAll() {
return userDao.getAll();
}
@GetMapping("/getUserById")
@ApiOperation(value = "根據id獲取用戶", notes = "id必傳", httpMethod = "GET")
@ApiImplicitParam(name = "id", value = "用戶id",example = "1", required = true, dataType = "long", paramType = "query")
public UserEntity getOne(Long id) {
return userDao.getOne(id);
}
@PostMapping("/getUserByNameAndSex")
@ApiOperation(value = "根據name和sex獲取用戶", notes = "", httpMethod = "POST")
@ApiImplicitParams({
@ApiImplicitParam(name = "userName", value = "用戶名", example = "關羽", required = true, dataType = "string", paramType = "query"),
@ApiImplicitParam(name = "userSex", value = "用戶性別", example = "男", required = true, dataType = "string", paramType = "query") })
public UserEntity getUserByNameAndSex(String userName, String userSex) {
return userDao.getUserByNameAndSex(userName, userSex);
}
@PostMapping("/insertUser")
@ApiOperation(value = "新增用戶", notes = "傳json,數據放body", httpMethod = "POST")
@ApiImplicitParams({
@ApiImplicitParam(name = "body", value = "用戶對象json", example = "{userName:'朝霧輕寒',userSex:'男'}", required = true) })
public String insertUser(@RequestBody String body) {
System.out.println(body);
UserEntity user = JSON.parseObject(body, UserEntity.class);
userDao.insertUser(user);
return "{code:0,msg:'success'}";
}
@PostMapping("/updateUser")
@ApiOperation(value = "修改用戶", notes = "傳json,數據放body", httpMethod = "POST")
@ApiImplicitParams({
@ApiImplicitParam(name = "body", value = "用戶對象json", example = "{id:23,userName:'朝霧輕寒',userSex:'女'}", required = true) })
public String updateUser(@RequestBody String body) {
System.out.println(body);
UserEntity user = JSON.parseObject(body, UserEntity.class);
userDao.updateUser(user);
return "{code:0,msg:'success'}";
}
@PostMapping("/deleteUser")
@ApiOperation(value = "刪除用戶", notes = "id必傳", httpMethod = "POST")
public String deleteUser(@ApiParam(name = "id", value = "用戶id", required = true) Long id) {
userDao.deleteUser(id);
return "{code:0,msg:'success'}";
}
}
訪問 http://127.0.0.1:8080/swagger-ui.html 進行接口在線測試
用于類,表示表示這個類是swagger的資源。屬性如下:
用于方法,表示一個http請求的操作。屬性如下:
用于方法、參數、字段說明;表示對參數的添加元數據。
用于類,表示對類進行說明,用于參數用實體類接受。
用于方法、字段,表示對model屬性的說明或者數據操作更改。
用于類、方法、方法參數,表示這個方法或者類被忽略,不在swagger-ui.html上顯示。
用于方法,表示單獨的請求參數。
用于方法,包含多個 @ApiImplicitParam。
用于類或者方法,描述操作的可能響應。
用于方法,響應頭設置。
添加依賴
<!-- swagger2markup 相關依賴 -->
<dependency>
<groupId>io.github.swagger2markup</groupId>
<artifactId>swagger2markup</artifactId>
<version>1.3.3</version>
</dependency>
轉換工具類
public class SwaggerUtils {
private static final String url = "http://127.0.0.1:8080/v2/api-docs";
/**
* 生成AsciiDocs格式文檔
* @throws MalformedURLException
*/
public static void generateAsciiDocs() throws MalformedURLException {
Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
.withMarkupLanguage(MarkupLanguage.ASCIIDOC)
.withOutputLanguage(Language.ZH)
.withPathsGroupedBy(GroupBy.TAGS)
.withGeneratedExamples()
.withoutInlineSchema().build();
Swagger2MarkupConverter.from(new URL(url))
.withConfig(config)
.build()
.toFolder(Paths.get("./docs/asciidoc/generated"));
}
/**
* 生成AsciiDocs格式文檔,并匯總成一個文件
* @throws MalformedURLException
*/
public static void generateAsciiDocsToFile() throws MalformedURLException {
Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
.withMarkupLanguage(MarkupLanguage.ASCIIDOC)
.withOutputLanguage(Language.ZH)
.withPathsGroupedBy(GroupBy.TAGS)
.withGeneratedExamples()
.withoutInlineSchema()
.build();
Swagger2MarkupConverter.from(new URL(url))
.withConfig(config)
.build()
.toFile(Paths.get("./docs/asciidoc/generated/all"));
}
/**
* 生成Markdown格式文檔
* @throws MalformedURLException
*/
public static void generateMarkdownDocs() throws MalformedURLException {
Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
.withMarkupLanguage(MarkupLanguage.MARKDOWN)
.withOutputLanguage(Language.ZH)
.withPathsGroupedBy(GroupBy.TAGS)
.withGeneratedExamples()
.withoutInlineSchema()
.build();
Swagger2MarkupConverter.from(new URL(url))
.withConfig(config)
.build()
.toFolder(Paths.get("./docs/markdown/generated"));
}
/**
* 生成Markdown格式文檔,并匯總成一個文件
* @throws MalformedURLException
*/
public static void generateMarkdownDocsToFile() throws MalformedURLException {
Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
.withMarkupLanguage(MarkupLanguage.MARKDOWN)
.withOutputLanguage(Language.ZH)
.withPathsGroupedBy(GroupBy.TAGS)
.withGeneratedExamples()
.withoutInlineSchema()
.build();
Swagger2MarkupConverter.from(new URL(url))
.withConfig(config)
.build()
.toFile(Paths.get("./docs/markdown/generated/all"));
}
/**
* 生成Confluence格式文檔
* @throws MalformedURLException
*/
public static void generateConfluenceDocs() throws MalformedURLException {
Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
.withMarkupLanguage(MarkupLanguage.CONFLUENCE_MARKUP)
.withOutputLanguage(Language.ZH)
.withPathsGroupedBy(GroupBy.TAGS)
.withGeneratedExamples()
.withoutInlineSchema()
.build();
Swagger2MarkupConverter.from(new URL(url))
.withConfig(config)
.build()
.toFolder(Paths.get("./docs/confluence/generated"));
}
/**
* 生成Confluence格式文檔,并匯總成一個文件
* @throws MalformedURLException
*/
public static void generateConfluenceDocsToFile() throws MalformedURLException {
Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
.withMarkupLanguage(MarkupLanguage.CONFLUENCE_MARKUP)
.withOutputLanguage(Language.ZH)
.withPathsGroupedBy(GroupBy.TAGS)
.withGeneratedExamples()
.withoutInlineSchema()
.build();
Swagger2MarkupConverter.from(new URL(url))
.withConfig(config)
.build()
.toFile(Paths.get("./docs/confluence/generated/all"));
}
}
使用測試 Controller
@RestController
@RequestMapping("/export")
@ApiIgnore
public class ExportController {
@RequestMapping("/ascii")
public String exportAscii() throws MalformedURLException{
SwaggerUtils.generateAsciiDocs();
return "success";
}
@RequestMapping("/asciiToFile")
public String asciiToFile() throws MalformedURLException{
SwaggerUtils.generateAsciiDocsToFile();
return "success";
}
@RequestMapping("/markdown")
public String exportMarkdown() throws MalformedURLException{
SwaggerUtils.generateMarkdownDocs();
return "success";
}
@RequestMapping("/markdownToFile")
public String exportMarkdownToFile() throws MalformedURLException{
SwaggerUtils.generateMarkdownDocsToFile();
return "success";
}
@RequestMapping("/confluence")
public String confluence() throws MalformedURLException{
SwaggerUtils.generateConfluenceDocs();
return "success";
}
@RequestMapping("/confluenceToFile")
public String confluenceToFile() throws MalformedURLException{
SwaggerUtils.generateConfluenceDocsToFile();
return "success";
}
}
添加依賴
<!--離線文檔 -->
<dependency>
<groupId>org.springframework.restdocs</groupId>
<artifactId>spring-restdocs-mockmvc</artifactId>
<scope>test</scope>
</dependency>
<!--springfox-staticdocs 生成靜態文檔 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-staticdocs</artifactId>
<version>2.6.1</version>
</dependency>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>io.github.swagger2markup</groupId>
<artifactId>swagger2markup-maven-plugin</artifactId>
<version>1.3.1</version>
<configuration>
<swaggerInput>http://127.0.0.1:8080/v2/api-docs</swaggerInput>
<outputDir>./docs/asciidoc/generated</outputDir>
<config>
<swagger2markup.markupLanguage>ASCIIDOC</swagger2markup.markupLanguage>
</config>
</configuration>
</plugin>
<plugin>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctor-maven-plugin</artifactId>
<version>1.5.3</version>
<!-- <version>2.0.0-RC.1</version> -->
<!-- Include Asciidoctor PDF for pdf generation -->
<dependencies>
<dependency>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctorj-pdf</artifactId>
<version>1.5.0-alpha.10.1</version>
</dependency>
<dependency>
<groupId>org.jruby</groupId>
<artifactId>jruby-complete</artifactId>
<version>1.7.21</version>
</dependency>
</dependencies>
<configuration>
<sourceDirectory>./docs/asciidoc/generated</sourceDirectory>
<outputDirectory>./docs/asciidoc/html</outputDirectory>
<backend>html</backend>
<!-- <outputDirectory>./docs/asciidoc/pdf</outputDirectory>
<backend>pdf</backend> -->
<headerFooter>true</headerFooter>
<doctype>book</doctype>
<sourceHighlighter>coderay</sourceHighlighter>
<attributes>
<!-- 菜單欄在左邊 -->
<toc>left</toc>
<!-- 多標題排列 -->
<toclevels>3</toclevels>
<!-- 自動打數字序號 -->
<sectnums>true</sectnums>
</attributes>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
可以修改此處 html 和 pdf,通過 mvn asciidoctor:process-asciidoc 可以導出相應格式文件
<outputDirectory>./docs/asciidoc/html</outputDirectory>
<backend>html</backend>
執行 mvn asciidoctor:process-asciidoc 后再執行 mvn generate-resources,可在 targt/generated-docs 目錄下生成 xml 格式文件
*請認真填寫需求信息,我們會在24小時內與您取得聯系。