swagger2.0與spring結合

官方文檔:
 
swagger是一個先後端api統一文檔和測試框架,注意,不光是一個api文檔,還能夠測試
 
  • 怎麼使用呢 這裏慢慢道來,咱們通常用的都是maven工程,因此這裏直接上maven依賴
<swagger.version>1.5.8</swagger.version>
<io.springfox.version>2.5.0</io.springfox.version>
<!-- swagger start -->
<dependency>
  <groupId>io.swagger</groupId>
  <artifactId>swagger-core</artifactId>
  <version>${swagger.version}</version>
</dependency>
<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger2</artifactId>
  <version>${io.springfox.version}</version>
</dependency>
<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger-ui</artifactId>
  <version>${io.springfox.version}</version>
</dependency>
<!-- swagger end -->

 

 
  • 這裏咱們須要注入SwaggerConfiguration配置,直接上代碼
/**
 * Created by max on 8/16/16.
 *
 */
@EnableSwagger2
public class SwaggerConfiguration {

    @Bean
    public Docket getApiInfo() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("outer api")
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build()
                .apiInfo(outApiInfo());

    }

    private ApiInfo outApiInfo() {
        return new ApiInfo(
                "mylearn 先後端接口-外部", // title 標題
                "外部接口文檔", // description 描述 標題下
                "1.0.0", // version
                "http://mylearn/*", // termsOfService
                new Contact("xieyuebin","","xieyuebin@meituan.com"), // contact
                "Apache 2.0", // licence
                "http://www.apache.org/licenses/LICENSE-2.0.html" // licence url
        );

    }

    @Bean
    public UiConfiguration getUiConfig() {
        return new UiConfiguration(
                null,// url,暫不用
                "none",       // docExpansion          => none | list
                "alpha",      // apiSorter             => alpha
                "schema",     // defaultModelRendering => schema
                UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS,
                false,        // enableJsonEditor      => true | false
                true);        // showRequestHeaders    => true | false
    }
這是對於文檔的說明以及ui的一些配置
 
  • 而後咱們還須要把swagger和spring mvc結合起來,首先在web.xml里加入swagger文檔的訪問路徑:
<!-- swagger ui 的靜態資源交由default處理-->
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>/swagger-ui.html</url-pattern>
    </servlet-mapping>

 

 
  • 而後咱們在dispatch-servlet.xml里加入對swagger靜態資源jar包的訪問路徑以下:
<!-- swagger 配置 ,線上版本須要註釋掉 -->
    <beans:bean class="com.meituan.maxtse.mylearn.swagger.SwaggerConfiguration"/>
    <!-- swagger ui resources-->
    <mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars"/>

 

這裏咱們用到了咱們前面定義的SwaggerConfiguration類
  • 而後咱們在controller和請求參數和返回參數里加入swagger提供的註解,直接上例子
入參:
/**
 * Created by max on 10/11/16.
 */
@ApiModel(description = "用戶請求表單")
public class UserForm {

    @ApiModelProperty(value = "姓名", example = "maxTse",position = 1)
    private String username;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Override
    public String toString() {
        return "UserForm{" +
                "username='" + username + '\'' +
                '}';
    }
}

 

返回值:
@JsonInclude(JsonInclude.Include.NON_NULL)
@ApiModel
public class OutResult<T> implements Serializable {

    @ApiModelProperty(value = "數據", example = "")
    public T data;

    @ApiModelProperty(value = "狀態碼,0表示成功 其餘表示失敗", example = "0")
    public int status;

    @ApiModelProperty(value = "錯誤信息", example = "操做成功")
    public String message = "";

 

controller:
/**
 * Created by max on 8/16/16.
 */
@Controller
@RequestMapping(value = "/test", consumes = "application/json", produces = "application/json")
public class TestController {

    private static final Logger LOGGER = LoggerFactory.getLogger(TestController.class);

    @ApiOperation(value = "swagger test", notes = "swagger test first", tags = {SwaggerConstants.TEST_TAG})
    @ResponseBody
    @RequestMapping(value = "/first", method = RequestMethod.POST)
    public OutResult<String> first(@RequestBody UserForm userForm) {
        LOGGER.info("first userForm={}", userForm);
        throw new RuntimeException("dd");
/*
        return OutResult.successResult(userForm.getUsername());
*/
    }

 

這裏挨個註解解釋下:
@ApiModel 代表這是一個被swagger框架管理的model,用於class上
@ApiModelProperty 這裏顧名思義,就是標註在被標註了@ApiModel的class的屬性上,
這裏的value是對字段的描述,example是取值例子,注意這裏的example頗有用,對於先後端開發工程師理解文檔起到了關鍵的做用,由於會在api文檔頁面上顯示出這些取值來;這個註解還有一些字段取值,能夠本身研究,舉例說一個:position,代表字段在model中的順序
@ApiOperation標註在具體請求上,value和notes的做用差很少,都是對請求進行說明;tags則是對請求進行分類的,好比你有好幾個controller,分別屬於不一樣的功能模塊,那這裏咱們就可使用tags來區分了,看上去頗有條理
  • 下面咱們啓動項目,而後經過url:localhost:8080/swagger-ui.html來訪問,就能夠看到swagger文檔界面了 

 

這裏是請求和返回結果的界面,看到這個界面是否是對剛纔咱們貼出來的具體例子裏的註解上的每一個值有所瞭解了,一一對應便能瞭解他們的做用
咱們開始說了,這個不只能夠當文檔使,並且還能夠進行測試,沒錯,看看參數界面你們都知道了,實際上參數界面就在請求和返回結果的下面:
 
看到右上方的大紅框,就是咱們的入參格式,注意,這裏是json格式的
而後咱們能夠在具體填入本身的請求參數後,點擊下方的try it out按鈕,就能夠進行測試了。
總結:
使用swagger2.0框架大概這麼幾步:
1.添加maven依賴
2.編寫SwaggerConfiguration配置
3.web.xml裏添加swagger文檔的訪問路徑,是靜態資源
4.添加相關的spring mvc配置
5.在請求的入參和返回值 以及具體的請求上添加相應的註解
6.啓動項目,訪問swagger.html
注意
因爲這裏使用的是json格式的入參和返回值,那麼咱們在controller的請求參數那裏要加上@RequestBody註解,而且請求方法必須是post
相關文章
相關標籤/搜索