1. 程式人生 > >整合Swagger2構建API文件

整合Swagger2構建API文件

修改pom檔案,新增swagger2的相關依賴

  <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>

 

 

新建一個swagger的配置類SwaggerConfig.java

package cn.enjoy.utils;

 

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import springfox.documentation.builders.ApiInfoBuilder;

import springfox.documentation.builders.PathSelectors;

import springfox.documentation.builders.RequestHandlerSelectors;

import springfox.documentation.service.ApiInfo;

import springfox.documentation.service.Contact;

import springfox.documentation.spi.DocumentationType;

import springfox.documentation.spring.web.plugins.Docket;

import springfox.documentation.swagger2.annotations.EnableSwagger2;

 

@Configuration

@EnableSwagger2

public class SwaggerConfig {

 

    @Bean

    public Docket createRestApi() {

        return new Docket(DocumentationType.SWAGGER_2)

                .apiInfo(apiInfo())

                .select()

                .apis(RequestHandlerSelectors.basePackage("cn.enjoy"))// 指定掃描包下面的註解

                .paths(PathSelectors.any())

                .build();

    }

    // 建立api的基本資訊

    private ApiInfo apiInfo() {

        return new ApiInfoBuilder()

                .title("整合Swagger2構建RESTful APIs")

                .description("整合Swagger2構建RESTful APIs")

                .termsOfServiceUrl("http://www.xiangxueketang.cn/")

                .contact(new Contact("enjoy","cn.xiangxueketang","[email protected]"))

                .version("1.0.0")

                .build();

    }

}

 

新建Controller用於顯示相關介面

package cn.enjoy.controller;

 

 

import io.swagger.annotations.ApiImplicitParam;

import io.swagger.annotations.ApiOperation;

import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RestController;

 

import java.util.HashMap;

import java.util.Map;

 

@RestController

@RequestMapping(value="/swagger")

public class SwaggerController {

    @ApiOperation(value="獲取使用者資訊", notes="根據id來獲取使用者詳細資訊")

    @ApiImplicitParam(name="id", value="使用者ID", required=true, dataType="String")

    @RequestMapping(value="/{id}", method= RequestMethod.GET)

    public Map<String,String> getInfo(@PathVariable String id) {

        Map<String ,String> map = new HashMap<String, String>();

        map.put("name", "lison");

        map.put("age", "38");

        return map;

    }

}

 

訪問:http://localhost