一、spring boot项目创建并引入swagger-ui所需jar包
dependencies {
// https://mvnrepository.com/artifact/io.springfox/springfox-swagger2
compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.7.0'
// https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui
compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.7.0'
}
二、配置swagger-ui
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
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())
.pathMapping("/")
.select() // 选择那些路径和api会生成document
.apis(RequestHandlerSelectors.any())// 对所有api进行监控
.apis(RequestHandlerSelectors.basePackage("com.controller")) // 选择要扫描控制类所在的包
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("swagger ui")
.description("测试swagger-ui")
.termsOfServiceUrl("http://www.gm.com")
.contact(new Contact("有问题?点 ↓", "https://www.baidu.com/", "xxx@qq.com"))
.version("1.0")
.build();
}
}
三、创建controller类
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@Api(description = "TestController")
@RequestMapping("/test")
@RestController
public class TestController {
@ApiOperation("hello swagger")
@RequestMapping(value = "/saveClothing",method = RequestMethod.POST)
@ApiImplicitParams({
@ApiImplicitParam(name = "name",value = "姓名",dataType = "String",paramType = "query"),
@ApiImplicitParam(name = "age",value = "年龄",dataType = "Integer",paramType = "query")
})
public String saveClothing(String name,Integer age){
return "你好";
}
}
四、运行结果
http://localhost:9090/swagger-ui.html#!/
五、常用注解
- @Api()用于类;
表示标识这个类是swagger的资源
- @ApiOperation()用于方法;
表示一个http请求的操作
- @ApiParam()用于方法,参数,字段说明;
表示对参数的添加元数据(说明或是否必填等)
- @ApiModel()用于类
表示对类进行说明,用于参数用实体类接收
- @ApiModelProperty()用于方法,字段
表示对model属性的说明或者数据操作更改
- @ApiIgnore()用于类,方法,方法参数
表示这个方法或者类被忽略
- @ApiImplicitParam() 用于方法
表示单独的请求参数
- @ApiImplicitParams() 用于方法,包含多个 @ApiImplicitParam