您的位置:首页 > 编程语言 > Java开发

Spring Boot 集成Swagger2

2016-08-22 15:28 337 查看
第一步: 在pom.xml文件中引入Swagger2的包

<properties>
<springfox.version>2.2.2</springfox.version>
</properties>

<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${springfox.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${springfox.version}</version>
</dependency>


第二步: 编写Swagger的控制类

@Configuration
@EnableSwagger2
public class SwaggerConfiguration implements EnvironmentAware {
private final Logger log = LoggerFactory.getLogger(SwaggerConfiguration.class);
public static final String DEFAULT_INCLUDE_PATTERN = "/.*";
private RelaxedPropertyResolver propertyResolver;

@Override
public void setEnvironment(Environment environment) {
this.propertyResolver = new RelaxedPropertyResolver(environment, "swagger.");
}

@Bean
public Docket swaggerSpringfoxDocket() {
StopWatch watch = new StopWatch();
watch.start();
Docket swaggerSpringMvcPlugin = new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.genericModelSubstitutes(ResponseEntity.class)
.select()
//设置需要扫描的web包路径,去掉自带的BaseErrorController测试接口,只显示自己包下面的接口
.apis(RequestHandlerSelectors.basePackage("com.vx.jk"))
.paths(regex(SwaggerConfiguration.DEFAULT_INCLUDE_PATTERN))
.build();
watch.stop();
return swaggerSpringMvcPlugin;
}

private ApiInfo apiInfo() {
return new ApiInfo(
propertyResolver.getProperty("title"),
propertyResolver.getProperty("description"),
propertyResolver.getProperty("version"),
propertyResolver.getProperty("termsOfServiceUrl"),
propertyResolver.getProperty("contact"),
propertyResolver.getProperty("license"),
propertyResolver.getProperty("licenseUrl")
);
}

}


第三步:写一个测试的web类

package com.vx.jk.web;

@RestController
@RequestMapping("jk")
@Api(value = "测试Controller", description = "测试类")
public class PhotoPriceController {

private static Logger LOG = LoggerFactory.getLogger(PhotoPriceController.class);

/*
@ApiOperation(value = “接口说明”, httpMethod = “接口请求方式”, response = “接口返回参数类型”, notes = “接口发布说明”;其他参数可参考源码;
@ApiParam(required = “是否必须参数”, name = “参数名称”, value = “参数具体描述”
@RequestParam(value = "id") 再get请求时,已id=数据值的形式拼接到url的?后面,如果不加,参数可能接受不到数据
@RequestBody 添加在输入参数上时,标识输入的数据是一个body体对象,如果不加,post提交的对象数据,参数可能接受不到数据,并且一个接口只能有一个body参数
*/
@ApiOperation(value = "输入ID",httpMethod="GET", notes = "返回字符串", response = String.class)
@RequestMapping(value = "/home", method = RequestMethod.GET)
public String home(@ApiParam(name="id", value="编号", required=true)@RequestParam(value = "id") String id,
HttpServletRequest request){
System.out.println(id+"------"+request.getParameter("id"));
return "helloworld"+id;
}
}


第四步; 启动项目 测试Swagger是否成功。

访问路径:http://localhost:8080/项目名/swagger-ui.html



输入字符111后的返回结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  swagger springboot