最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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繼承中是否創(chuàng)建父類對象

    淺談java繼承中是否創(chuàng)建父類對象

    下面小編就為大家?guī)硪黄獪\談java繼承中是否創(chuàng)建父類對象。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-06-06
  • SpringBoot如何整合SpringDataJPA

    SpringBoot如何整合SpringDataJPA

    這篇文章主要介紹了SpringBoot整合SpringDataJPA代碼實例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-02-02
  • jackson 如何將實體轉(zhuǎn)json json字符串轉(zhuǎn)實體

    jackson 如何將實體轉(zhuǎn)json json字符串轉(zhuǎn)實體

    這篇文章主要介紹了jackson 實現(xiàn)將實體轉(zhuǎn)json json字符串轉(zhuǎn)實體,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-10-10
  • Spring Security整合KeyCloak保護(hù)Rest API實現(xiàn)詳解

    Spring Security整合KeyCloak保護(hù)Rest API實現(xiàn)詳解

    這篇文章主要為大家介紹了Spring Security整合KeyCloak保護(hù)Rest API實現(xiàn)實例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-11-11
  • SpringBoot做junit測試的時候獲取不到bean的解決

    SpringBoot做junit測試的時候獲取不到bean的解決

    這篇文章主要介紹了SpringBoot做junit測試的時候獲取不到bean的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-09-09
  • java中的String定義的字面量最大長度是多少

    java中的String定義的字面量最大長度是多少

    這篇文章主要介紹了java中的String定義的字面量最大長度是多少,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-12-12
  • MyBatis動態(tài)SQL標(biāo)簽的用法詳解

    MyBatis動態(tài)SQL標(biāo)簽的用法詳解

    這篇文章主要介紹了MyBatis動態(tài)SQL標(biāo)簽的用法詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-04-04
  • 詳解Spring boot上配置與使用mybatis plus

    詳解Spring boot上配置與使用mybatis plus

    這篇文章主要介紹了詳解Spring boot上配置與使用mybatis plus,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-05-05
  • MyBatis快速入門

    MyBatis快速入門

    MyBatis是支持普通SQL查詢,存儲過程和高級映射的優(yōu)秀持久層框架。MyBatis消除了幾乎所有的JDBC代碼和參數(shù)的手工設(shè)置以及結(jié)果集的檢索。想要學(xué)好它,那就要從MyBatis基礎(chǔ)知識學(xué)起,下面跟著小編一起來看下吧
    2017-03-03
  • Spring?BeanFactory?與?FactoryBean?的區(qū)別詳情

    Spring?BeanFactory?與?FactoryBean?的區(qū)別詳情

    這篇文章主要介紹了Spring?BeanFactory?與?FactoryBean?的區(qū)別詳情,BeanFactory?和?FactoryBean?的區(qū)別卻是一個很重要的知識點,在本文中將結(jié)合源碼進(jìn)行分析講解,需要的小伙伴可以參考一下
    2022-05-05

最新評論

栾川县| 无锡市| 芦山县| 普兰县| 南京市| 广平县| 商城县| 延边| 桑植县| 墨江| 集贤县| 新乡市| 泰兴市| 廉江市| 五家渠市| 民乐县| 临沭县| 枣阳市| 监利县| 城固县| 金塔县| 奎屯市| 措美县| 三门峡市| 灌阳县| 丹阳市| 二手房| 宜君县| 阿坝县| 祁阳县| 怀远县| 正阳县| 赤城县| 太康县| 杭锦后旗| 西充县| 江山市| 农安县| 江永县| 台东市| 松原市|