一、导入依赖
<!-- 图像化依赖 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<!--引入swagger2依赖 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
注意:springboot版本不允许太高,这里是2.5.6版本
二、建立一个config包(一般放所有的配置类)
在SwaggerConfig里里面写入配置信息
@Configuration
@EnableSwagger2
public class SwaggerConfig implements WebMvcConfigurer {
@Bean
public Docket createRestAPi() {
// 构造函数传入初始化规范,这是swagger2规范
return new Docket(DocumentationType.SWAGGER_2)
// apiInfo:添加api的详情信息,参数为ApiInfo类型的参数,这个参数包含了基本描述信息:比如标题、描述、版本之类的,开发中一般都是自定义这些信息
.apiInfo(apiInfo())
// select、apis、paths、build 这四个是一组的,组合使用才能返回一个Docket实例对象,其中apis和paths是可选的。
.select()
// apis:添加过滤条件。RequestHandlerSelectors中有很多过滤方式;RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class):加了ApiOperation注解的类,生成接口文档
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
// paths:控制那些路径的api会被显示出来。
.paths(PathSelectors.any())
.build()
// 是否开启swagger 如果是false,浏览器将无法访问,默认是true
.enable(true)
;
}
/**
* 页面信息展示
* @return
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
// 标题内容
.title("API文档")
// 描述内容
.description("接口文档详情信息")
// 版本
.version("1.0")
// 联系人信息
.contact(new Contact("", "", ""))
// 许可
.license("")
// 许可链接
.licenseUrl("")
.build();
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations(
"classpath:/static/");
registry.addResourceHandler("swagger-ui.html").addResourceLocations(
"classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations(
"classpath:/META-INF/resources/webjars/");
WebMvcConfigurer.super.addResourceHandlers(registry);
}
}
三、启动项目,打开浏览器http://localhost:8080/swagger-ui.html访问
四、使用swagger
一般我们使用swagger都存储在controller层里
swagger相关注解
@Api(tags = {"测试信息接口"})//写在类上的注解,对当前类的描述
@ApiOperation(value = "插入测试信息" )//写对方法的描述,与@API要一起用这两个注解才会生效
显示
注:如果是入参是个对象的话,不能写 注释数组提示