SpringBoot整合Swagger
导入Swagger所需的依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
配置Swagger,创建SwaggerConfig.java类
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
//注解开启 swagger2功能
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
.groupName("swaggerText")
.select()
// 扫描的路劲包,设置basePackage会将包下的所有被@Api标记类的所有方法作为api
.apis(RequestHandlerSelectors.basePackage("com"))
// 指定路径处理PathSelectors.any()表示所有的路径
.paths(PathSelectors.any()).build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("这里是APi文档名称")
.description("这里是对api的接口描述")
//服务条款
.termsOfServiceUrl("https://gitee.com/S760620329")
//联系信息
.contact(new Contact("笑一笑","https://gitee.com/S760620329","760620329@qq.com"))
.version("1.0").build();
}
}
创建controller,测试运行
@RestController
@RequestMapping("/text")
@Api(value = "测试接口", tags = "textController")
public class TextController {
@ApiOperation(value = "获取id", notes = "根据url的id来获取详细信息")
/*
paramType:指定参数放在哪个地方
path:用于restful接口-->请求参数的获取:@PathVariable
*/
@ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Long", paramType = "path")
@GetMapping("/{id}")
public String annotate(@PathVariable int id) {
return "you id is :" + id;
}
}
在启动类上添加注解
@ComponentScan(basePackages = {"com.xujc"}) // 扫描swagger所在的包
@EnableSwagger2 // 开启swagger
启动Swagger
访问 http://localhost:8080/swagger-ui.html 即可看到 Swagger-UI
常用注解说明
@Api:用于controller类上,说明该类的作用
- tags:"说明该类的作用,可以在ui界面上看到的注解"
- value:"该参数没有意义,在ui界面上也看不到,所以不需要配置"
@ApiOperation:用在controller的方法上,用来说明方法用途、作用
- value= "说明方法的用途、作用"
- notes= "方法的备注说明"
@ApiParam:用来给controller的参数增加说明
- name:参数名
- value:参数的汉字说明、解释
- required:参数是否必传,true必传
@ApiModelProperty:用于entity、vo类上; 表示对model属性的说明或者数据操作更改
- value:字段说明
- example:举例说明
@ApiIgnore:使用该注解忽略这个Api,不会生成接口文档,可注解才类和方法上