SpringBoot Swagger2 接口規(guī)范示例詳解
如今,REST
和微服務(wù)已經(jīng)有了很大的發(fā)展勢頭。但是,REST
規(guī)范中并沒有提供一種規(guī)范來編寫我們的對外REST
接口API
文檔。每個人都在用自己的方式記錄api
文檔,因此沒有一種標(biāo)準(zhǔn)規(guī)范能夠讓我們很容易的理解和使用該接口。我們需要一個共同的規(guī)范和統(tǒng)一的工具來解決文檔的難易理解文檔的混亂格式。Swagger
(在谷歌、IBM
、微軟等公司的支持下)做了一個公共的文檔風(fēng)格來填補(bǔ)上述問題。在本博客中,我們將會學(xué)習(xí)怎么使用Swagger
的 Swagger2
注解去生成REST API
文檔。
Swagger
(現(xiàn)在是“開放API
計劃”)是一種規(guī)范和框架,它使用一種人人都能理解的通用語言來描述REST API
。還有其他一些可用的框架,比如RAML
、求和等等,但是 Swagger是最受歡迎的。它提供了人類可讀和機(jī)器可讀的文檔格式。它提供了JSON
和UI
支持。JSON
可以用作機(jī)器可讀的格式,而Swagger-UI
是用于可視化的,通過瀏覽api
文檔,人們很容易理解它。
一、添加 Swagger2 的 maven依賴
打開項目中的 pom.xml文件,添加以下兩個 swagger依賴。springfox-swagger2 、springfox-swagger-ui。
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.6.1</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.6.1</version> </dependency>
實際上,Swagger的 API有兩種類型,并在不同的工件中維護(hù)。今天我們將使用 springfox,因為這個版本可以很好地適應(yīng)任何基于 spring的配置。我們還可以很容易地嘗試其他配置,這應(yīng)該提供相同的功能——配置中沒有任何變化。
二、添加 Swagger2配置
使用 Java config的方式添加配置。為了幫助你理解這個配置,我在代碼中寫了相關(guān)的注釋:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import com.google.common.base.Predicates; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableSwagger2 public class Swagger2UiConfiguration extends WebMvcConfigurerAdapter { @Bean public Docket api() { // @formatter:off //將控制器注冊到 swagger //還配置了Swagger 容器 return new Docket(DocumentationType.SWAGGER_2).select() .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.any()) //掃描 controller所有包 .apis(Predicates.not(RequestHandlerSelectors.basePackage("org.springframework.boot"))) .paths(PathSelectors.any()) .paths(PathSelectors.ant("/swagger2-demo")) .build(); // @formatter:on } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { //為可視化文檔啟用swagger ui部件 registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); } }
通過 api()方法返回 Docket,調(diào)用以下方法:
【1】apiInfo()方法中可以添加 api文檔的基本信息(具體類型查看文檔);
【2】select()方法返回 ApiSelectorBuilder實例,用于過濾哪些 api需要顯示;
【3】apis()方法中填寫項目中 Controller類存放的路徑;
最后 build()建立 Docket。
三、驗證 Swagger2的 JSON格式文檔
在application.yml中配置服務(wù)名為:swagger2-demo
server.contextPath=/swagger2-demo
maven
構(gòu)建并啟動服務(wù)器。打開鏈接,會生成一個JSON
格式的文檔。這并不是那么容易理解,實際上Swagger
已經(jīng)提供該文檔在其他第三方工具中使用,例如當(dāng)今流行的 API管理工具,它提供了API網(wǎng)關(guān)、API緩存、API文檔等功能。
四、驗證 Swagger2 UI文檔
打開鏈接 在瀏覽器中來查看Swagger UI
文檔;
五、Swagger2 注解的使用
默認(rèn)生成的 API文檔很好,但是它們?nèi)狈υ敿?xì)的 API級別信息。Swagger提供了一些注釋,可以將這些詳細(xì)信息添加到 api中。如。@Api
我們可以添加這個注解在 Controller上,去添加一個基本的 Controller說明。
@Api(value = "Swagger2DemoRestController", description = "REST APIs related to Student Entity!!!!") @RestController public class Swagger2DemoRestController { //... }
@ApiOperation and @ApiResponses我們添加這個注解到任何 Controller的 rest方法上來給方法添加基本的描述。例如:
@ApiOperation(value = "Get list of Students in the System ", response = Iterable.class, tags = "getStudents") @ApiResponses(value = { @ApiResponse(code = 200, message = "Success|OK"), @ApiResponse(code = 401, message = "not authorized!"), @ApiResponse(code = 403, message = "forbidden!!!"), @ApiResponse(code = 404, message = "not found!!!") }) @RequestMapping(value = "/getStudents") public List<Student> getStudents() { return students; }
在這里,我們可以向方法中添加標(biāo)簽,來在 swagger-ui中添加一些分組。@ApiModelProperty這個注解用來在數(shù)據(jù)模型對象中的屬性上添加一些描述,會在 Swagger UI中展示模型的屬性。例如:
@ApiModelProperty(notes = "Name of the Student",name="name",required=true,value="test name") private String name;
Controller 和 Model 類添加了swagger2注解之后,代碼清單:Swagger2DemoRestController.java
import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.example.springbootswagger2.model.Student; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; @Api(value = "Swagger2DemoRestController", description = "REST Apis related to Student Entity!!!!") @RestController public class Swagger2DemoRestController { List<Student> students = new ArrayList<Student>(); { students.add(new Student("Sajal", "IV", "India")); students.add(new Student("Lokesh", "V", "India")); students.add(new Student("Kajal", "III", "USA")); students.add(new Student("Sukesh", "VI", "USA")); } @ApiOperation(value = "Get list of Students in the System ", response = Iterable.class, tags = "getStudents") @ApiResponses(value = { @ApiResponse(code = 200, message = "Suceess|OK"), @ApiResponse(code = 401, message = "not authorized!"), @ApiResponse(code = 403, message = "forbidden!!!"), @ApiResponse(code = 404, message = "not found!!!") }) @RequestMapping(value = "/getStudents") public List<Student> getStudents() { return students; } @ApiOperation(value = "Get specific Student in the System ", response = Student.class, tags = "getStudent") @RequestMapping(value = "/getStudent/{name}") public Student getStudent(@PathVariable(value = "name") String name) { return students.stream().filter(x -> x.getName().equalsIgnoreCase(name)).collect(Collectors.toList()).get(0); } @ApiOperation(value = "Get specific Student By Country in the System ", response = Student.class, tags = "getStudentByCountry") @RequestMapping(value = "/getStudentByCountry/{country}") public List<Student> getStudentByCountry(@PathVariable(value = "country") String country) { System.out.println("Searching Student in country : " + country); List<Student> studentsByCountry = students.stream().filter(x -> x.getCountry().equalsIgnoreCase(country)) .collect(Collectors.toList()); System.out.println(studentsByCountry); return studentsByCountry; } // @ApiOperation(value = "Get specific Student By Class in the System ",response = Student.class,tags="getStudentByClass") @RequestMapping(value = "/getStudentByClass/{cls}") public List<Student> getStudentByClass(@PathVariable(value = "cls") String cls) { return students.stream().filter(x -> x.getCls().equalsIgnoreCase(cls)).collect(Collectors.toList()); } }
Student.java
實體類
import io.swagger.annotations.ApiModelProperty; public class Student { @ApiModelProperty(notes = "Name of the Student",name="name",required=true,value="test name") private String name; @ApiModelProperty(notes = "Class of the Student",name="cls",required=true,value="test class") private String cls; @ApiModelProperty(notes = "Country of the Student",name="country",required=true,value="test country") private String country; public Student(String name, String cls, String country) { super(); this.name = name; this.cls = cls; this.country = country; } public String getName() { return name; } public String getCls() { return cls; } public String getCountry() { return country; } @Override public String toString() { return "Student [name=" + name + ", cls=" + cls + ", country=" + country + "]"; } }
六、swagger-ui 展示
現(xiàn)在,當(dāng)我們的 REST api得到適當(dāng)?shù)淖⑨寱r,讓我們看看最終的輸出。打開http://localhost:8080/swagger2-demo/swagger-ui。在瀏覽器中查看 Swagger ui
文檔。
到此這篇關(guān)于SpringBoot Swagger2 接口規(guī)范的文章就介紹到這了,更多相關(guān)SpringBoot Swagger2 接口內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java 數(shù)據(jù)庫時間返回前端顯示錯誤(差8個小時)的解決方法
本文主要介紹了Java 數(shù)據(jù)庫時間返回前端顯示錯誤(差8個小時)的解決方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-08-08Spring中@RabbitHandler和@RabbitListener的區(qū)別詳析
@RabbitHandler是用于處理消息的方法注解,它與@RabbitListener注解一起使用,這篇文章主要給大家介紹了關(guān)于Spring中@RabbitHandler和@RabbitListener區(qū)別的相關(guān)資料,需要的朋友可以參考下2024-02-02java實時監(jiān)控文件行尾內(nèi)容的實現(xiàn)
這篇文章主要介紹了java實時監(jiān)控文件行尾內(nèi)容的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-02-02解析Java中所有錯誤和異常的父類java.lang.Throwable
這篇文章主要介紹了Java中所有錯誤和異常的父類java.lang.Throwable,文章中簡單地分析了其源碼,說明在代碼注釋中,需要的朋友可以參考下2016-03-03Spring RedisTemplate 批量獲取值的2種方式小結(jié)
這篇文章主要介紹了Spring RedisTemplate 批量獲取值的2種方式小結(jié),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-06-06