1.pom.xml****添加依赖(版本号2.5.0以上):
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
2. 启动类 Application.java 同级目录下新增Swagger2.java配置类。
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
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.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* Swagger2配置类
* 在与spring boot集成时,放在与Application.java同级的目录下。
* 通过@Configuration注解,让Spring来加载该类配置。
* 再通过@EnableSwagger2注解来启用Swagger2。
*/
@Configuration
@EnableSwagger2
public class Swagger2 {
@Value("${swagger.enable:false}")
private boolean enableSwagger; // 是否启用Swagger 默认值为false, 设置默认值防止获取不到值时报错
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.enable(enableSwagger)
.select()
//此包路径下的类,才生成接口文档
.apis(RequestHandlerSelectors.basePackage("com.kang.xmService"))
//加了ApiOperation注解的方法,才生成接口文档
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("公共服务接口 APIs")
.description("这个是说明")
.version("0.1.1")
.build();
}
}
3.在类上添加注解
@Api(tags = "XmController", description = "项目API")。
4.在要暴露的方法上添加注解
@RequestMapping(value ="/retrieve", method= RequestMethod.POST)
@ApiOperation(notes = " 入参:查询条件", value="列表查询")
注意:@ApiOperation注解必须有,因为在Swagger2.java配置类中扫描的该注解, @RequestMapping注解最好指定一个请求方式POST或者GET或者其他,不指定将会解析出多个相同方法,但请求方式不同的URL。
5.在入参前添加注解
@ApiParam(value = "请求参数", required = true)。
具体value、required是否必填根据情况选择。
6.访问 http://localhost:8080/xmService/swagger-ui.html
7.测试
1)点击Try it out,输入参数
2)点击Execute执行相应方法的测试。
3)在Server response中可以查看返回值。