Swagger框架學習分享

轉至元數據結尾
轉至元數據起始

1、背景介紹

1.1.項目簡單介紹

Swagger項目是由Dilip Krishnan和Adrian Kelly等人維護開發的一個爲Spring Web MVC 項目提供方法文檔的一個框架。該框架最基本的功能是將Controller的方法進行可視化的展示,像方法凝視。方法參數,方法返回值等都提供了對應的用戶界面。尤爲是對JSON參數的支持。同一時候可以結合swagger-ui可以對用戶界面進行不一樣程度的定製,也可以對方法進行一個簡單的測試。css

1.2.code repository

1.3.演示項目

2、開發準備

2.1.環境準備

  • idea intellij 13+
  • Oracle java 1.6
  • Gradle 2.0 +

2.2.項目搭建

2.2.1.jar倉庫

Mavenhtml

<repositories>
     <repository>
       <id>jcenter-release</id>
       <name>jcenter</name>
       <url>http: //oss.jfrog.org/artifactory/oss-release-local/</url>
     </repository>
</repositories>
 
<dependency>
     <groupId>com.mangofactory</groupId>
     <artifactId>swagger-springmvc</artifactId>
     <version> 1.0 . 0 </version>
</dependency>

Gradlejava

repositories {
     jcenter()
}
 
compile  "com.mangofactory:swagger-springmvc:1.0.0"

2.2.2.相關依賴

  • As of v0.9.5 all dependencies on scala have been removed.
  • Spring 3.2.x or above
  • jackson 2.4.4
  • guava 15.0

2.2.3.編寫配置文件

編寫一個Java文件,並使用註解:git

  • @Configuration 配置註解,本身主動在本類上下文載入一些環境變量信息
  • @EnableWebMvc 
  • @EnableSwagger 使swagger生效
  • @ComponentScan("com.myapp.packages") 需要掃描的包路徑

演示樣例:github

package org.bugkillers.back.swagger;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import com.mangofactory.swagger.configuration.SpringSwaggerConfig;
import com.mangofactory.swagger.models.dto.ApiInfo;
import com.mangofactory.swagger.paths.SwaggerPathProvider;
import com.mangofactory.swagger.plugin.EnableSwagger;
import com.mangofactory.swagger.plugin.SwaggerSpringMvcPlugin;
/**
 * 使用註解的方式來掃描API
 * 無需在Spring的xml配置文件來配置。由 @see @EnableWebMvc 取代
 * <p/>
 * <p> @author 劉新宇
 *
 * <p> @date 2015年1月30日 下午1:18:48
 * <p> @version 0.0.1
 */
@Configuration
@EnableWebMvc
@EnableSwagger
@ComponentScan(basePackages ={"com.ak.swaggerspringmvc.shared.controller", "com.ak.spring3.music"})
public class CustomJavaPluginConfig extends WebMvcConfigurerAdapter {
   private SpringSwaggerConfig springSwaggerConfig;
   @Autowired
   public void setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig) {
      this.springSwaggerConfig = springSwaggerConfig;
   }
   /**
    * 鏈式編程 來定製API樣式
    * 興許會加上分組信息
    * @return
    */
   @Bean
   public SwaggerSpringMvcPlugin customImplementation(){
      return new SwaggerSpringMvcPlugin(this.springSwaggerConfig)
            .apiInfo(apiInfo())
            .includePatterns(".*")
//            .pathProvider(new GtPaths())
            .apiVersion("0.0.1")
            .swaggerGroup("user");
   }
    private ApiInfo apiInfo() {
      ApiInfo apiInfo = new ApiInfo(
              "bugkillers-back API",
              "bugkillers 後臺API文檔",
              "<a href="http://127.0.0.1:9081/api" "="" style="color: rgb(59, 115, 175); text-decoration: none; border-radius: 0px !important; border: 0px !important; bottom: auto !important; float: none !important; height: auto !important; left: auto !important; margin: 0px !important; outline: 0px !important; overflow: visible !important; padding: 0px !important; position: static !important; right: auto !important; top: auto !important; vertical-align: baseline !important; width: auto !important; box-sizing: content-box !important; min-height: inherit !important; background: none !important;">http://127.0.0.1:9081/api",
              "bugkillers@163.com",
              "My License",
              "My Apps API License URL"
        );
      return apiInfo;
    }
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
      configurer.enable();
    }
     
    class GtPaths extends SwaggerPathProvider{
        @Override
        protected String applicationPath() {
            return "/restapi";
        }
        @Override
        protected String getDocumentationPath() {
            return "/restapi";
        }
    }
     
}

 

 也可以本身不寫配置類,直接使用默認的實現類,在Spring的配置文件裏共配置:(不推薦web

1
2
<mvc:annotation-driven/> <!-- Required so swagger-springmvc can access spring's RequestMappingHandlerMapping  -->
<bean  class = "com.mangofactory.swagger.configuration.SpringSwaggerConfig"  />

 

2.2.4.與swagger-ui集成

方式一:spring

  • Note: Only use this option if you don't need to customize any of the swagger-ui static content, otherwise use option 2.
  • Use the web-jar which packages all of the swagger-ui static content.
  • Requires that your app is using the servlet 3 specification.
  • For non-spring boot applications some extra spring configuration (ResourceHandler's) is required. See: https://github.com/adrianbk/swagger-springmvc-demo/tree/master/swagger-ui
1
2
3
4
dependencies {
   ...
   compile  "org.ajar:swagger-spring-mvc-ui:0.4"
}

方式二:(推薦編程

  • Manually copy all of the static content swagger-ui's dist directory (https://github.com/wordnik/swagger-ui/tree/master/dist)
  • Provide the necessary view resolvers and resource handlers to serve the static content.
  • Consult the spring documentation on serving static resources.

The following is one way to serve static content from /src/main/webappapi

1
2
3
4
5
<!-- Direct  static  mappings -->
<mvc:resources mapping= "*.html"  location= "/" />
 
<!-- Serve  static  content-->
<mvc: default -servlet-handler/>

2.6.5.Controller配置

使用註解對Controller進行配置:spring-mvc

  • @Api 配置方法API
  • @ApiOperation API的操做 GET PUT DELETE POST
  • @ApiParam API的方法參數描寫敘述

演示樣例Controller:

package org.bugkillers.back.user.controller;
import java.util.List;
import org.bugkillers.back.bean.User;
import org.bugkillers.back.result.Result;
import org.bugkillers.back.user.service.UserService;
import org.bugkillers.back.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
/**
 * 用戶操做Controller
 * <p/>
 * <p>
 *
 * @author 劉新宇
 *
 *         <p>
 * @date 2015年1月30日 上午10:50:34
 *       <p>
 * @version 0.0.1
 */
@Api(value = "user-api", description = "有關於用戶的CURD操做", position = 5)
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService service;
    /**
     * 注冊用戶
     * @param user
     */
    @ApiOperation(value = "註冊", notes = "注冊用戶", position = 3)
    @ResponseBody
    @RequestMapping(value = { "/regist" }, method = RequestMethod.POST)
    public ResponseEntity<?

> regist(@RequestBody User user) { service.save(user); Result<String> result = ResultUtil.buildSuccessResult("註冊成功"); return new ResponseEntity<Result<String>>(result, HttpStatus.OK); } /** * 依據pk查找用戶 * @param userPk * @return */ @ApiOperation(value = "依據pk查找用戶", notes = "返回用戶實體對象", response = User.class, position = 2) @ResponseBody @RequestMapping(value = { "/{userPk}" }, method = RequestMethod.GET) public ResponseEntity<?> findByPk( @ApiParam(value = "填寫Pk", allowableValues = "range[1,5]", required = true, defaultValue = "userPk", allowMultiple = true) @PathVariable("userPk") Integer userPk) { Result<User> result = ResultUtil.buildSuccessResult(service.findByPk(userPk)); return new ResponseEntity<Result<User>>(result, HttpStatus.OK); } /** * 測試 * @param who * @return */ @ApiOperation(value = "Hellow World", notes = "測試功能", position = 1) @ResponseBody @RequestMapping(value = { "/hello/{who}" }, method = RequestMethod.GET) public ResponseEntity<?

> hello( @ApiParam(value = "填寫名稱") @PathVariable("who") String who) { Result<String> result = ResultUtil.buildSuccessResult( "Hello guys" + " " + who + "!"); return new ResponseEntity<Result<String>>(result, HttpStatus.OK); } /** * 查詢所有 * @return */ @ApiOperation(value = "獲取所有用戶", notes = "返回用戶實體對象集合", position = 5) @RequestMapping(value = "/findAll", method = RequestMethod.GET) public @ResponseBody ResponseEntity<?> findAll() { Result<List<User>> result = ResultUtil.buildSuccessResult( service.findAll()); return new ResponseEntity<Result<List<User>>>(result, HttpStatus.OK); } /** * 依據用戶pk更新實體 * @param userPk 用戶pk * @param user 返回更新後的實體 * @return */ @ApiOperation(value = "更新用戶", notes = "返回更新的用戶實體對象",position = 5) @RequestMapping(value = "/update/{userPk}", method = RequestMethod.PUT) public ResponseEntity<?> updateByPk( @PathVariable("userPk") Integer userPk, @RequestBody User user) { user.setPk_user(userPk); service.update(user); Result<User> result = ResultUtil.buildSuccessResult(user); return new ResponseEntity<Result<User>>(result, HttpStatus.OK); } /** * 依據用戶pk刪除實體 * @param userPk 用戶pk * @return */ @ApiOperation(value = "刪除用戶", notes = "依據pk刪除用戶",position = 5) @RequestMapping(value = "/delete/{userPk}", method = RequestMethod.GET) public ResponseEntity<?> deleteByPk( @PathVariable("userPk") Integer userPk) { service.delete(userPk); Result<String> result = ResultUtil.buildSuccessResult("刪除成功"); return new ResponseEntity<Result<String>>(result, HttpStatus.OK); } }



2.2.6.啓動中間件

項目配置了Jetty或者Tomcat等Web容器的話,在相應的Controller配置好的話就可以啓動看效果了。

2.2.7.需求定製

  • 分組信息定製
  • Url定製
  • Http對應定製

 

3、學習感想

Swagger很是好的爲咱們在開發RESTful框架應用時,先後臺分離的狀況下提供了很是有效的解決方式。上手迅速,操做簡單,界面精簡,功能無缺。知足各類定製化的需求,是在使用Spring MVC作Web開發時的不二選擇。

經過對swagger的學習。加強了英語交流的能力。改變了曾經的學習方法。收穫了很是多,同一時候也也得感謝國外友人的悉心幫助~技術無國界~

3.1  Guava工具類的使用  http://ifeve.com/google-guava/

Guavaproject包括了若干被Google的 Java項目普遍依賴 的核心庫,好比:集合 [collections] 、緩存 [caching] 、原生類型支持 [primitives support] 、併發庫 [concurrency libraries] 、通用註解 [common annotations] 、字符串處理 [string processing] 、I/O 等等

3.2  Gradle構建工具的使用  http://ifeve.com/google-guava/

配置更加簡潔。支持Maven,好多開源項目已經從Maven轉到Gradle。

3.3  Groovy語言 http://groovy.codehaus.org/User+Guide

和scala、clojure等同是在JVM上執行的腳本語言,豐富的類庫。和Java互通。可以做爲Java程序猿的第二語言。

3.4  鏈式編程 (return this

Java中相似Swagger配置文件SwaggerSpringMvcPlugin

JQuery中相似 $("#p1").css("color","red").slideUp(2000).slideDown(2000);



在公司的Wiki上寫的博文。因爲外面訪問不了公司的內網,故貼過來給需要的小夥伴們分享一下,有疑問的可以隨時交流。

相關文章
相關標籤/搜索