亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

SpringBoot Swagger2 接口規(guī)范示例詳解

 更新時間:2023年12月01日 16:25:38   作者:程序猿進(jìn)階  
Swagger(在谷歌、IBM、微軟等公司的支持下)做了一個公共的文檔風(fēng)格來填補(bǔ)上述問題,在本文中,我們將會學(xué)習(xí)怎么使用Swagger的 Swagger2注解去生成REST API文檔,感興趣的朋友一起看看吧

如今,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í)怎么使用SwaggerSwagger2注解去生成REST API文檔。

Swagger(現(xiàn)在是“開放 API計劃”)是一種規(guī)范和框架,它使用一種人人都能理解的通用語言來描述REST API。還有其他一些可用的框架,比如RAML、求和等等,但是 Swagger是最受歡迎的。它提供了人類可讀和機(jī)器可讀的文檔格式。它提供了JSONUI支持。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個小時)的解決方法

    本文主要介紹了Java 數(shù)據(jù)庫時間返回前端顯示錯誤(差8個小時)的解決方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-08-08
  • Spring中@RabbitHandler和@RabbitListener的區(qū)別詳析

    Spring中@RabbitHandler和@RabbitListener的區(qū)別詳析

    @RabbitHandler是用于處理消息的方法注解,它與@RabbitListener注解一起使用,這篇文章主要給大家介紹了關(guān)于Spring中@RabbitHandler和@RabbitListener區(qū)別的相關(guān)資料,需要的朋友可以參考下
    2024-02-02
  • java生成餅圖svg及JFreeChart生成svg圖表

    java生成餅圖svg及JFreeChart生成svg圖表

    java生成餅圖svg,代碼實現(xiàn)感覺有點復(fù)雜,個人認(rèn)為不如用JFreeChart,這篇文章主要介紹java生成餅圖svg及JFreeChart生成svg圖表,有需要的小伙伴可以參考下
    2015-08-08
  • java實時監(jiān)控文件行尾內(nèi)容的實現(xiàn)

    java實時監(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使用位運算實現(xiàn)加減乘除詳解

    Java使用位運算實現(xiàn)加減乘除詳解

    這篇文章主要為大家詳細(xì)介紹了Java如何使用位運算實現(xiàn)加減乘除,文中的示例代碼講解詳細(xì),對我們深入了解Java有一定的幫助,感興趣的可以了解一下
    2023-05-05
  • Java中駝峰命名與下劃線命名相互轉(zhuǎn)換

    Java中駝峰命名與下劃線命名相互轉(zhuǎn)換

    這篇文章主要介紹了Java中駝峰命名與下劃線命名相互轉(zhuǎn)換,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-01-01
  • SWT(JFace)體驗之StyledText類

    SWT(JFace)體驗之StyledText類

    有的時候Text需要實現(xiàn)這種那種的樣式。先提供在不使用StyledText類的情況:
    2009-06-06
  • 解析Java中所有錯誤和異常的父類java.lang.Throwable

    解析Java中所有錯誤和異常的父類java.lang.Throwable

    這篇文章主要介紹了Java中所有錯誤和異常的父類java.lang.Throwable,文章中簡單地分析了其源碼,說明在代碼注釋中,需要的朋友可以參考下
    2016-03-03
  • Spring RedisTemplate 批量獲取值的2種方式小結(jié)

    Spring RedisTemplate 批量獲取值的2種方式小結(jié)

    這篇文章主要介紹了Spring RedisTemplate 批量獲取值的2種方式小結(jié),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-06-06
  • 淺談一下Java中的幾種JVM級別的鎖

    淺談一下Java中的幾種JVM級別的鎖

    這篇文章主要介紹了淺談一下Java中的幾種JVM級別的鎖,當(dāng)存在安全漏洞時,也必須有相應(yīng)的防護(hù)措施。順應(yīng)這種趨勢,虛擬"鎖"被發(fā)明出來,以解決線程的安全問題。在這篇文章中,我們將研究多年來出現(xiàn)的?Java?中幾種典型的?JVM?級鎖,需要的朋友可以參考下
    2023-08-08

最新評論