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

Java利用Swagger2自動生成對外接口的文檔

 更新時間:2018年06月26日 09:23:15   作者:小賣鋪的老爺爺  
這篇文章主要介紹了Java利用Swagger2自動生成對外接口的文檔,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

一直以來做對外的接口文檔都比較原始,基本上都是手寫的文檔傳來傳去,最近發(fā)現(xiàn)了一個新玩具,可以在接口上省去不少麻煩。

swagger是一款方便展示的API文檔框架。它可以將接口的類型最全面的展示給對方開發(fā)人員,避免了手寫文檔的片面和誤差行為。

swagger目前有兩種swagger和swagger2兩種,1比較麻煩,所以不考慮使用。本文主要記錄我用swagger2做對外接口的兩種方式,方面后面查閱。

一、使用傳統(tǒng)的springmvc整合swagger2

1、maven依賴

<!--springfox依賴-->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.8.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.6.3</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.6.3</version>
    </dependency>
    <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger2</artifactId>
      <version>2.4.0</version>
    </dependency>
    <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger-ui</artifactId>
      <version>2.4.0</version>
    </dependency>

2、spring-mvc.xml 中添加映射靜態(tài)的配置(其實我項目中把這個去掉也可以,不知道什么情況):

<!-- swagger靜態(tài)文件路徑 -->
  <mvc:resources location="classpath:/META-INF/resources/" mapping="swagger-ui.html"/> 
  <mvc:resources location="classpath:/META-INF/resources/webjars/" mapping="/webjars/**"/>

注意:基本的springmvc配置我就不貼了,需要注意的是,如果你看到swagger-ui.html 界面出來,但卻一片空白,請檢查下你web.xml中攔截器的配置,一定要springmvc先攔截到,然后界面才會顯示的。

3、然后是swagger2的配置類:

@Configuration
@EnableSwagger2
public class SwaggerConfig extends WebMvcConfigurationSupport {

  @Bean
  public Docket createRestApi() {
    return new Docket(DocumentationType.SWAGGER_2)
        .apiInfo(apiInfo())
        .select()
        .apis(RequestHandlerSelectors.basePackage("net.laoyeyey.yyblog"))
        .paths(PathSelectors.any())
        .build();
  }

  private ApiInfo apiInfo() {
    return new ApiInfoBuilder()
        .title("yyblog項目 RESTful APIs")
        .description("yyblog項目api接口文檔")
        .version("1.0")
        .build();
  }
}

注意:paths如果在生產(chǎn)情況下可以調(diào)整為PathSelectors.none(),即不顯示所有接口信息;

4、接口信息配置

即在SpringMvc的Controller中配置相關(guān)的接口信息

@Controller
@RequestMapping(value = "aitou")
@Api(description = "測試服務(wù)-賬戶信息查詢")
public class DailyOperationDataController {
  Logger      logger  = Logger.getLogger(DailyOperationDataController.class);
  @Autowired
  private DailyOperationDataService DailyOperationDataService;
  /* 
   * @ApiOperation(value = "接口說明", httpMethod ="接口請求方式", response ="接口返回參數(shù)類型", notes ="接口發(fā)布說明" 
   * @ApiParam(required = "是否必須參數(shù)", name ="參數(shù)名稱", value ="參數(shù)具體描述"
   */
  @ApiOperation(value = "賬戶信息查詢接口")
  @RequestMapping(method ={RequestMethod.POST,RequestMethod.GET}, value="/query/dailydata/{dataDate}")
  @ResponseBody
  public DailyOperationDataDto getDailyReportByDataDate(@PathVariable("dataDate") String dataDate) {
    try {
      return DailyOperationDataService.getDailyReportByDataDate(dataDate);
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
    }

    return null;
  }

}

注:通常情況下swagger2會將掃描包下所有的接口展示出來,這里我是對外的接口是單獨一個包,避免展示過多的接口,當然接口方法也可以讓它不展示??梢栽谙旅婵吹较嚓P(guān)的注解中有寫。

常用的一些注解

@Api:用在類上,說明該類的作用
@ApiOperation:用在方法上,說明方法的作用
@ApiImplicitParams:用在方法上包含一組參數(shù)說明
@ApiImplicitParam:用在 @ApiImplicitParams 注解中,指定一個請求參數(shù)的各個方面
  paramType:參數(shù)放在哪個地方
  · header --> 請求參數(shù)的獲取:@RequestHeader
  · query -->請求參數(shù)的獲?。篅RequestParam
  · path(用于restful接口)--> 請求參數(shù)的獲?。篅PathVariable
  · body(不常用)
  · form(不常用)
  name:參數(shù)名
  dataType:參數(shù)類型
  required:參數(shù)是否必須傳
  value:參數(shù)的意思
  defaultValue:參數(shù)的默認值
@ApiResponses:用于表示一組響應(yīng)
@ApiResponse:用在@ApiResponses中,一般用于表達一個錯誤的響應(yīng)信息
  code:數(shù)字,例如400
  message:信息,例如"請求參數(shù)沒填好"
  response:拋出異常的類
@ApiParam:單個參數(shù)描述
@ApiModel:描述一個Model的信息,用對象來接收參數(shù)(這種一般用在post創(chuàng)建的時候,使用@RequestBody這樣的場景,請求參數(shù)無法使用@ApiImplicitParam注解進行描述的時候)
@ApiModelProperty:描述一個model的屬性
@ApiProperty:用對象接收參數(shù)時,描述對象的一個字段
@ApiIgnore:使用該注解忽略這個API

基本上就是上面這些了,是不是很easy,下面看下效果圖

二、使用springboot整合swagger2

上面說了使用傳統(tǒng)的springmvc整合swagger2,在說說最近比較流行的springboot的方式,其實原理都是一樣的。

1、maven依賴

<!--springfox依賴 -->
    <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger2</artifactId>
      <version>2.7.0</version>
    </dependency>
    <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger-ui</artifactId>
      <version>2.7.0</version>
    </dependency>

這個是我最近用springboot寫的個人項目中的內(nèi)用,版本用的2.7.0

2、添加靜態(tài)資源配置

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {/**
   * 配置靜態(tài)資源路徑以及上傳文件的路徑
   *
   * @param registry
   */
  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    registry.addResourceHandler("/upload/**").addResourceLocations(environment.getProperty("spring.resources.static-locations"));
    /*swagger-ui*/
    registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
    registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
  }

}

其實就是最后兩句,如果你不配置這個的話,訪問swagger-ui.html會出現(xiàn)500,還是404的錯誤來著,記不清了,應(yīng)該是404.

3、swagger2的配置類

和上面一樣,基本上沒區(qū)別

@Configuration
@EnableSwagger2
@EnableWebMvc
public class SwaggerConfig extends WebMvcConfigurationSupport {

  @Bean
  public Docket createRestApi() {
    return new Docket(DocumentationType.SWAGGER_2)
        .apiInfo(apiInfo())
        .select()
        .apis(RequestHandlerSelectors.basePackage("net.laoyeye.yyblog.web.frontend"))
        .paths(PathSelectors.none())
        .build();
  }

  private ApiInfo apiInfo() {
    return new ApiInfoBuilder()
        .title("yyblog項目 RESTful APIs")
        .description("yyblog項目api接口文檔")
        .version("1.0")
        .build();
  }


}

注意,我上面有說path的問題哦,直接拷貝不顯示api的,(#^.^#)

4、接口的配置

/**
 * 前臺文章Controller
 * @author 小賣鋪的老爺爺
 * @date 2018年5月5日
 * @website www.laoyeye.net
 */
@Api(description="文章查詢")
@Controller
@RequestMapping("/article")
public class ArticleController {
  @Autowired
  private ArticleService articleService;
  @Autowired
  private SettingService settingService;
  @Autowired
  private CateService cateService;
  @Autowired
  private TagReferService tagReferService;
  @Autowired
  private UserService userService;
  @Autowired
  private ArticleMapper articleMapper;
  @Autowired
  private CommentService commentService;
  
  @ApiOperation(value="文章查詢接口")
  @ApiImplicitParam(name = "id", value = "文章ID", required = true, dataType = "Long")
  @GetMapping("/{id}")
  public String index(Model model, @PathVariable("id") Long id) {
    try {
      articleService.updateViewsById(id);
    } catch (Exception ignore) {
    }
    List<Setting> settings = settingService.listAll();
    Map<String,Object> map = new HashMap<String,Object>();
    for (Setting setting : settings) {
      map.put(setting.getCode(), setting.getValue());
    }
    Article article = articleService.getArticleById(id);
    model.addAttribute("settings", map);
    model.addAttribute("cateList", cateService.listAllCate());
    model.addAttribute("article", article);
    model.addAttribute("tags", tagReferService.listNameByArticleId(article.getId()));
    model.addAttribute("author", userService.getNicknameById(article.getAuthorId()));
    //回頭改
    model.addAttribute("articles", articleMapper.listArticleByTitle(null));
    model.addAttribute("similars", articleMapper.listArticleByTitle(null));
    CommentQuery query = new CommentQuery();
    query.setLimit(10);
    query.setPage(1);
    query.setArticleId(id);
    model.addAttribute("comments", commentService.listCommentByArticleId(query));
    return "frontend/article";
  }
  
  @ApiOperation(value="文章評論查詢接口")
  @PostMapping("/comments")
  @ResponseBody
  public DataGridResult comments(CommentQuery query) {
    //設(shè)置默認10
    query.setLimit(10);
    return commentService.listCommentByArticleId(query);
  }
  
  @ApiOperation(value="文章點贊接口")
  @ApiImplicitParam(name = "articleId", value = "文章ID", required = true, dataType = "Long")
  @PostMapping("/approve")
  @ResponseBody
  public YYBlogResult approve(@RequestParam Long articleId) {
    return articleService.updateApproveCntById(articleId);
  }
}

最后同樣來個效果圖,和上面一樣。

PathSelectors.none()的時候


PathSelectors.any()的時候


看到效果圖是不是接口內(nèi)容一目了然,很簡潔明了了。

最后,好像忘記說swagger文檔的路徑了

如果你的項目在根目錄:http://localhost:8080/swagger-ui.html

如果不是根目錄那就是:http://localhost:8080/你的項目名/swagger-ui.html

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

您可能感興趣的文章:

相關(guān)文章

  • Gradle:修改默認的Build配置文件名方式

    Gradle:修改默認的Build配置文件名方式

    這篇文章主要介紹了Gradle:修改默認的Build配置文件名方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-03-03
  • Spring boot2+jpa+thymeleaf實現(xiàn)增刪改查

    Spring boot2+jpa+thymeleaf實現(xiàn)增刪改查

    這篇文章主要介紹了Spring boot2+jpa+thymeleaf實現(xiàn)增刪改查,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-04-04
  • Java Swing JPasswordField密碼框的實現(xiàn)示例

    Java Swing JPasswordField密碼框的實現(xiàn)示例

    這篇文章主要介紹了Java Swing JPasswordField密碼框的實現(xiàn)示例,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-12-12
  • IDEA2020.1常用配置說明

    IDEA2020.1常用配置說明

    這篇文章主要介紹了IDEA2020.1常用配置說明,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-06-06
  • 詳解java封裝實現(xiàn)Excel建表讀寫操作

    詳解java封裝實現(xiàn)Excel建表讀寫操作

    這篇文章給大家分享了java封裝實現(xiàn)Excel建表讀寫操作的相關(guān)知識點內(nèi)容,有需要的朋友們可以學(xué)習(xí)下。
    2018-08-08
  • Java算法之重新排列數(shù)組例題

    Java算法之重新排列數(shù)組例題

    這篇文章主要介紹了Java算法之重新排列數(shù)組例題,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,感興趣的小伙伴可以參考一下
    2022-08-08
  • Java實現(xiàn)的斷點續(xù)傳功能的示例代碼

    Java實現(xiàn)的斷點續(xù)傳功能的示例代碼

    本篇文章主要介紹了Java實現(xiàn)的斷點續(xù)傳功能的示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-02-02
  • 關(guān)于Java中修飾符的總結(jié)(fina除外)

    關(guān)于Java中修飾符的總結(jié)(fina除外)

    下面小編就為大家?guī)硪黄P(guān)于Java中修飾符的總結(jié)(fina除外)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2016-09-09
  • Jmeter實現(xiàn)Base64編碼的兩種方式

    Jmeter實現(xiàn)Base64編碼的兩種方式

    這篇文章主要介紹了Jmeter實現(xiàn)Base64編碼,大家都知道Jmeter實現(xiàn)Base64編碼有兩種方式,本文通過圖文并茂的形式把每種方法給大家介紹的非常詳細,需要的朋友可以參考下
    2022-01-01
  • Java集合類之Map集合的特點及使用詳解

    Java集合類之Map集合的特點及使用詳解

    這篇文章主要為大家詳細介紹一下Java集合類中Map的特點及使用,文中的示例代碼講解詳細,對我們學(xué)習(xí)Java有一定幫助,感興趣的可以了解一下
    2022-08-08

最新評論

巴中市| 保康县| 德安县| 牙克石市| 陆河县| 周至县| 桃园县| 扶余县| 务川| 喀喇| 武冈市| 分宜县| 黄梅县| 福建省| 大姚县| 田东县| 双鸭山市| 昂仁县| 靖宇县| 新和县| 太仆寺旗| 东乡族自治县| 贞丰县| 抚宁县| 灵璧县| 神农架林区| 满城县| 马公市| 连山| 紫云| 清远市| 文水县| 江源县| 乌拉特中旗| 九江县| 琼结县| 崇义县| 沙坪坝区| 洛隆县| 遂溪县| 东丽区|