一.Swagger的作用
swagger用于生成在线api文档和进行接口测试,是前后端联调中使用最多的工具
二.Swagger的详细使用步骤
1.引入Swagger依赖
<!--swagger-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<scope>provided </scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<scope>provided </scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<scope>provided </scope>
</dependency>
2.创建swagger配置类
import com.google.common.base.Predicates;
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.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 webApiConfig(){
return new Docket(DocumentationType.SWAGGER_2) //类型:swagger
.groupName("webApi") //分组名称
.apiInfo(webApiInfo()) //设置在线文档的信息
.select()
.paths(Predicates.not(PathSelectors.regex("/admin/.*")))
.paths(Predicates.not(PathSelectors.regex("/error.*")))
.build();
}
private ApiInfo webApiInfo(){
return new ApiInfoBuilder()
.title("网站-课程中心API文档")
.description("本文档描述了课程中心微服务接口定义")
.version("1.0")
.contact(new Contact("java", "http://atguigu.com", "[email protected]"))
.build();
}
}
3.若创建的swagger是新建的一个模块(若是在当前模块引入swager依赖,此步可以忽略),则:
(1)将swagger模块的坐标导入依赖到要使用swagger的模块中
(2)在启动类上添加@ComponentScan(basePackages={"swagger配置类所在的包路径"})
假设:swagger所在包:com.atguigu.servicebase
启动类所在包:com.atguigu.service
则配置为@ComponentScan(basePackages = {"com.atguigu"})
4.启动项目,访问http://ip:接口/swagger-ui.html进入swagger的控制台
若有弹窗问题,则要刷新maven,重启项目
5.接口测试
页面中已经显示了可以测试的接口,点击要测试的接口,value处输入参数,点击Try it out发送
6.swagger生成api文档的常用帮助注解:
以下这些注解用于生成api文档时,接口的提示信息
@Api(description = "讲师模块"):用在类上
@ApiOperation(value = "讲师列表"):用在方法上
@ApiParam(name = "id",value = "讲师id",required = true):用在参数上
@ApiModel:用在类上,标记类是swagger的解析类
属性: Value:为模型提供备用名称 description:提供详细的类描述
@ApiModelProperty:用在@A皮Model标记的类的属性上,
属性: Value: 属性简要说明
@ApiModel
效果如下:
版权归原作者 十八岁讨厌Java 所有, 如有侵权,请联系我们删除。