引入相关依赖
<!--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>
<properties>
<swagger.version>2.7.0</swagger.version>
</properties>
配置Swagger
@Configuration//配置类
@EnableSwagger2 //swagger注解
public class SwaggerConfig {
@Bean
public Docket webApiConfig(){
return new Docket(DocumentationType.SWAGGER_2)//Swagger类型
.groupName("webApi")//自定义Swagger名字
.apiInfo(webApiInfo())
.select()
.paths(Predicates.not(PathSelectors.regex("/admin/.*")))//当匹配到admin、error等字体时不显示操作
.paths(Predicates.not(PathSelectors.regex("/error.*")))
.build();
}
private ApiInfo webApiInfo(){
return new ApiInfoBuilder()//以下是在Swagger网站中显示的主页面
.title("网站-课程中心API文档")
.description("本文档描述了课程中心微服务接口定义")
.version("1.0")
.contact(new Contact("hk", "http://athk.com", "1123@qq.com"))
.build();
}
}
若要使用Swagger的模块跟Swagger配置类位置不一致,则要在需要用到Swagger的模块进行配置
@SpringBootApplication
@ComponentScan(basePackages = {"com.athk"})//找到Swagger存放位置的包名,扫描以这个命名的包下面的类,用途主要是要扫描其他模块的配置类
public class EduAppliction {
public static void main(String[] args) {
SpringApplication.run(EduAppliction.class,args);
}
}
接下来点击启动类,找到该模块使用的端口号,我用的是8001,然后浏览器打开http://localhost:8001/swagger-ui.html
就可以看到该模块下的controller下的接口了,也可以在接口中进行测试
以下是我controller定义的接口
@ApiOperation(value = "所有讲师列表")
//1.查询表所有数据
@GetMapping("findAll")
public List<EduTeacher> findAllTeacher(){
List<EduTeacher> list = eduTeacherService.list(null);
return list;
}
//2.删除教师
@ApiOperation(value = "逻辑删除讲师")
@DeleteMapping("{id}")//通过路径进行传递id
public boolean deleteTeacher( @ApiParam(name = "id", value = "讲师ID", required = true)
@PathVariable String id){//@PathVariable该注解用户获取路径的参数
boolean b = eduTeacherService.removeById(id);
return b;
}
}
Swagger页面呈现出来为
点开接口,我们可以看到接口的详情
点击**Try it out!**可以对接口进行测试。
使用Swagger可以看到接口的详情,方便前后端更好的交流测试。
本人使用springboot版本2.2.1。