欧美一区二区三区老妇人-欧美做爰猛烈大尺度电-99久久夜色精品国产亚洲a-亚洲福利视频一区二区

如何實(shí)現(xiàn)集成Swagger2開(kāi)發(fā)API文檔

本篇內(nèi)容主要講解“如何實(shí)現(xiàn)集成Swagger2開(kāi)發(fā)API文檔”,感興趣的朋友不妨來(lái)看看。本文介紹的方法操作簡(jiǎn)單快捷,實(shí)用性強(qiáng)。下面就讓小編來(lái)帶大家學(xué)習(xí)“如何實(shí)現(xiàn)集成Swagger2開(kāi)發(fā)API文檔”吧!

10年積累的成都網(wǎng)站設(shè)計(jì)、成都網(wǎng)站制作經(jīng)驗(yàn),可以快速應(yīng)對(duì)客戶(hù)對(duì)網(wǎng)站的新想法和需求。提供各種問(wèn)題對(duì)應(yīng)的解決方案。讓選擇我們的客戶(hù)得到更好、更有力的網(wǎng)絡(luò)服務(wù)。我雖然不認(rèn)識(shí)你,你也不認(rèn)識(shí)我。但先網(wǎng)站設(shè)計(jì)后付款的網(wǎng)站建設(shè)流程,更有陽(yáng)東免費(fèi)網(wǎng)站建設(shè)讓你可以放心的選擇與我們合作。

前言

相信很多后端開(kāi)發(fā)在項(xiàng)目中都會(huì)碰到要寫(xiě) api 文檔,不管是給前端、移動(dòng)端等提供更好的對(duì)接,還是以后為了以后交接方便,都會(huì)要求寫(xiě) api 文檔。

而手寫(xiě) api 文檔的話有諸多痛點(diǎn):

  • 文檔更新的時(shí)候,需要再次發(fā)送給對(duì)接人

  • 接口太對(duì),手寫(xiě)文檔很難管理

  • 接口返回的結(jié)果不明確

  • 不能直接在線測(cè)試接口,通常需要使用工具,如 postman 等

Swagger 就很好的解決了這個(gè)問(wèn)題。

Swagger 簡(jiǎn)介

Swagger 是一個(gè)規(guī)范和完整的框架,用于生成、描述、調(diào)用和可視化 RESTful 風(fēng)格的 Web 服務(wù)??傮w目標(biāo)是使客戶(hù)端和文件系統(tǒng)作為服務(wù)器以同樣的速度來(lái)更新。文件的方法,參數(shù)和模型緊密集成到服務(wù)器端的代碼,允許API來(lái)始終保持同步。

官網(wǎng):https://swagger.io

Swagger 使用

1.相關(guān)依賴(lài)

<!--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>

2.Swagger 配置類(lèi)

@Configuration
@EnableSwagger2
public class SwaggerConfig {
	@Bean
    public Docket buildDocket() {
        return new Docket(DocumentationType.SWAGGER_2)
        .apiInfo(buildApiInf()) //將api的元信息設(shè)置為包含在json resourcelisting響應(yīng)中
        //.host("127.0.0.1:8080") //設(shè)置ip和端口,或者域名
        .select()  //啟動(dòng)用于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")//文檔標(biāo)題
        .description("Swagger 示例 Restful Api 文檔")//文檔描述
        .contact(contact)//聯(lián)系人
        .version("1.0")//版本號(hào)
        //.license("")//更新此API的許可證信息
        //.licenseUrl("")//更新此API的許可證Url
        //.termsOfServiceUrl("")//更新服務(wù)條款URL
        .build();

    }
}

3.Spring MVC 相關(guān)配置

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
	/**
	 * 靜態(tài)資源配置(默認(rèn))
	 */
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");// 靜態(tài)資源路徑
		registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
		registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
		super.addResourceHandlers(registry);
	}


}

如果不添加此靜態(tài)資源配置會(huì)報(bào)錯(cuò),找不到相關(guān)路徑

4.Model 中使用 Swagger 注解

@ApiModel(value = "UserEntity", description = "用戶(hù)對(duì)象")
public class UserEntity implements Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = 5237730257103305078L;
	@ApiModelProperty(value ="用戶(hù)id",name="id",dataType="Long",required = false,example = "1",hidden = false )
	private Long id;
	@ApiModelProperty(value ="用戶(hù)名",name="userName",dataType="String",required = false,example = "關(guān)羽" )
	private String userName;
	@ApiModelProperty(value ="用戶(hù)性別",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;
	}

}

5. Controller 中使用 Swagger 注解

@RestController
@RequestMapping("/api")
@Api(tags = { "接口分組1", "接口分組2" })
public class ApiController {

	@Autowired
	private UserDao userDao;

	@GetMapping("/getAllUser")
	@ApiOperation(value = "獲取所有用戶(hù)", notes = "", httpMethod = "GET", tags = "接口分組3")
	public List<UserEntity> getAll() {
		return userDao.getAll();
	}

	@GetMapping("/getUserById")
	@ApiOperation(value = "根據(jù)id獲取用戶(hù)", notes = "id必傳", httpMethod = "GET")
	@ApiImplicitParam(name = "id", value = "用戶(hù)id",example = "1", required = true, dataType = "long", paramType = "query")
	public UserEntity getOne(Long id) {
		return userDao.getOne(id);
	}

	@PostMapping("/getUserByNameAndSex")
	@ApiOperation(value = "根據(jù)name和sex獲取用戶(hù)", notes = "", httpMethod = "POST")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "userName", value = "用戶(hù)名", example = "關(guān)羽", required = true, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "userSex", value = "用戶(hù)性別", example = "男", required = true, dataType = "string", paramType = "query") })
	public UserEntity getUserByNameAndSex(String userName, String userSex) {
		return userDao.getUserByNameAndSex(userName, userSex);
	}

	@PostMapping("/insertUser")
	@ApiOperation(value = "新增用戶(hù)", notes = "傳json,數(shù)據(jù)放body", httpMethod = "POST")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "body", value = "用戶(hù)對(duì)象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 = "修改用戶(hù)", notes = "傳json,數(shù)據(jù)放body", httpMethod = "POST")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "body", value = "用戶(hù)對(duì)象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 = "刪除用戶(hù)", notes = "id必傳", httpMethod = "POST")
	public String deleteUser(@ApiParam(name = "id", value = "用戶(hù)id", required = true) Long id) {
		userDao.deleteUser(id);
		return "{code:0,msg:'success'}";
	}
}

5.測(cè)試

訪問(wèn) http://127.0.0.1:8080/swagger-ui.html 進(jìn)行接口在線測(cè)試

Swagger 常用注解

1.@Api

用于類(lèi),表示標(biāo)識(shí)這個(gè)類(lèi)是swagger的資源。屬性如下:

  • tags 表示說(shuō)明,tags如果有多個(gè)值,會(huì)生成多個(gè)列表

  • value 表示說(shuō)明,可以使用tags替代

2.@ApiOperation

用于方法,表示一個(gè)http請(qǐng)求的操作。屬性如下:

  • value 用于方法描述

  • notes 用于提示內(nèi)容

  • tags 用于API文檔控制的標(biāo)記列表,視情況而用,可以進(jìn)行獨(dú)立分組

3.@ApiParam

用于方法、參數(shù)、字段說(shuō)明;表示對(duì)參數(shù)的添加元數(shù)據(jù)。

  • name 參數(shù)名

  • value 參數(shù)說(shuō)明

  • required 是否必填

4.@ApiModel

用于類(lèi),表示對(duì)類(lèi)進(jìn)行說(shuō)明,用于參數(shù)用實(shí)體類(lèi)接受。

  • value 對(duì)象名

  • description 描述

5.@ApiModelProperty

用于方法、字段,表示對(duì)model屬性的說(shuō)明或者數(shù)據(jù)操作更改。

  • value 字段說(shuō)明

  • name 重寫(xiě)屬性名

  • dataType 重寫(xiě)屬性數(shù)據(jù)類(lèi)型

  • required 是否必填

  • example 舉例說(shuō)明

  • hidden 隱藏

6.@ApiIgnore

用于類(lèi)、方法、方法參數(shù),表示這個(gè)方法或者類(lèi)被忽略,不在swagger-ui.html上顯示。

7.@ApiImplicitParam

用于方法,表示單獨(dú)的請(qǐng)求參數(shù)。

  • name 參數(shù)名

  • value 參數(shù)說(shuō)明

  • dataType 數(shù)據(jù)類(lèi)型

  • paramType 參數(shù)類(lèi)型

  • example 舉例說(shuō)明

8.@ApiImplicitParams

用于方法,包含多個(gè) @ApiImplicitParam。

9.@ApiResponses @ApiResponse

用于類(lèi)或者方法,描述操作的可能響應(yīng)。

  • code 響應(yīng)的HTTP狀態(tài)代碼

  • message 響應(yīng)附帶的可讀消息

10.@ResponseHeader

用于方法,響應(yīng)頭設(shè)置。

  • name 響應(yīng)頭名稱(chēng)

  • description 頭描述

  • response 默認(rèn)響應(yīng)類(lèi) void

  • responseContainer 參考ApiOperation中配置

Swagger 導(dǎo)出離線 api 文檔

1.導(dǎo)出 AsciiDocs、Markdown、Confluence 格式文檔

添加依賴(lài)

<!-- swagger2markup 相關(guān)依賴(lài) -->
		<dependency>
			<groupId>io.github.swagger2markup</groupId>
			<artifactId>swagger2markup</artifactId>
			<version>1.3.3</version>
		</dependency>

轉(zhuǎn)換工具類(lèi)

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格式文檔,并匯總成一個(gè)文件
	 * @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格式文檔,并匯總成一個(gè)文件
	 * @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格式文檔,并匯總成一個(gè)文件
	 * @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"));
	}
	
	
}

使用測(cè)試 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";
	}
}

2.導(dǎo)出 html、pdf、xml 格式

添加依賴(lài)

<!--離線文檔 -->
		<dependency>
			<groupId>org.springframework.restdocs</groupId>
			<artifactId>spring-restdocs-mockmvc</artifactId>
			<scope>test</scope>
		</dependency>
		<!--springfox-staticdocs 生成靜態(tài)文檔 -->
		<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>
							<!-- 多標(biāo)題排列 -->
							<toclevels>3</toclevels>
							<!-- 自動(dòng)打數(shù)字序號(hào) -->
							<sectnums>true</sectnums>
						</attributes>
					</configuration>					
				</plugin>
			</plugins>
		</pluginManagement>

	</build>

可以修改此處 html 和 pdf,通過(guò) mvn asciidoctor:process-asciidoc 可以導(dǎo)出相應(yīng)格式文件

<outputDirectory>./docs/asciidoc/html</outputDirectory> 
						<backend>html</backend>

執(zhí)行 mvn asciidoctor:process-asciidoc 后再執(zhí)行 mvn generate-resources,可在 targt/generated-docs 目錄下生成 xml 格式文件。

到此,相信大家對(duì)“如何實(shí)現(xiàn)集成Swagger2開(kāi)發(fā)API文檔”有了更深的了解,不妨來(lái)實(shí)際操作一番吧!這里是創(chuàng)新互聯(lián)網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢(xún),關(guān)注我們,繼續(xù)學(xué)習(xí)!

新聞名稱(chēng):如何實(shí)現(xiàn)集成Swagger2開(kāi)發(fā)API文檔
標(biāo)題路徑:http://chinadenli.net/article2/jsidic.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供營(yíng)銷(xiāo)型網(wǎng)站建設(shè)、網(wǎng)站維護(hù)用戶(hù)體驗(yàn)、動(dòng)態(tài)網(wǎng)站、域名注冊(cè)、網(wǎng)站營(yíng)銷(xiāo)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

營(yíng)銷(xiāo)型網(wǎng)站建設(shè)
国产精品午夜福利在线观看| 日本在线高清精品人妻| 男人大臿蕉香蕉大视频| 日韩一级一片内射视频4k| av免费视屏在线观看| 亚洲欧美精品伊人久久| 激情中文字幕在线观看| 加勒比系列一区二区在线观看| 成人精品视频在线观看不卡| 色婷婷视频在线精品免费观看| 国产一区二区不卡在线播放 | 好骚国产99在线中文| 亚洲欧洲在线一区二区三区| 国产偷拍精品在线视频| 激情五月天免费在线观看| 日本 一区二区 在线| 内射精品欧美一区二区三区久久久 | 噜噜中文字幕一区二区| 91欧美一区二区三区| 国产亚洲欧美日韩精品一区| 成人区人妻精品一区二区三区| 亚洲婷婷开心色四房播播| 色婷婷视频国产一区视频| 欧美日不卡无在线一区| 好吊妞视频这里有精品| 偷拍偷窥女厕一区二区视频| 人妻精品一区二区三区视频免精| 久久福利视频在线观看| 国内真实露脸偷拍视频| 欧美黑人在线一区二区| 亚洲欧美国产网爆精品| 精品日韩欧美一区久久| 免费大片黄在线观看国语| 99少妇偷拍视频在线| 午夜传媒视频免费在线观看| 日本加勒比不卡二三四区| 在线视频三区日本精品| 亚洲夫妻性生活免费视频| 日本av在线不卡一区| 亚洲一区二区三区有码| 亚洲精品福利视频你懂的|