修改pom文件,添加swagger2的相關依賴html
<dependency>java
<groupId>io.springfox</groupId>web
<artifactId>springfox-swagger2</artifactId>spring
<version>2.7.0</version>api
</dependency>app
<dependency>ui
<groupId>io.springfox</groupId>.net
<artifactId>springfox-swagger-ui</artifactId>htm
<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 {
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","enjoy@enjoy.cn"))
.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:8080/swagger-ui.html