1.添加pom依赖
<!-- Swagger2依赖 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>
<!--swagger2-ui依赖-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
</dependency>
2.创建swagger的配置类
package com.sdyy.api.main.config;
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;
/**
*
* * @className: Swagger2Config
* * @description:TODO
* * @param:
* * @return:
* * @throws:
* * @author: ml
* * @date: 2020/07/15 17:15
*
*/
@Configuration
@EnableSwagger2
public class Swagger2Config {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.pathMapping("/")
.select()
.apis(RequestHandlerSelectors.basePackage("com.sdyy.api.main.controller"))
.paths(PathSelectors.any())
.build().apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
// 页面标题
.title("SpringBoot整合Swagger2")
// 描述
.description("接口使用和调试")
//创建人信息
.contact(new Contact("mal", "https://www.cnblogs.com/zs-notes/category/1258467.html", "11@qq.com"))
// 版本号
.version("2.0")
.build();
}
}
3.使用swagger2来进行测试接口主要是在哪些类中使用:这里我们依然选择在controller层:
这里边涉及到多个API:
@Api注解可以用来标记当前Controller的功能。
@ApiOperation注解用来标记一个方法的作用。
@ApiImplicitParam注解用来描述一个参数,可以配置参数的中文含义,也可以给参数设置默认值,这样在接口测试的时候可以避免手动输入。
如果有多个参数,则需要使用多个@ApiImplicitParam注解来描述,多个@ApiImplicitParam注解需要放在一个@ApiImplicitParams注解中。
需要注意的是,@ApiImplicitParam注解中虽然可以指定参数是必填的,但是却不能代替@RequestParam(required = true),前者的必填只是在Swagger2框架内必填,抛弃了Swagger2,这个限制就没用了,所以假如开发者需要指定一个参数必填,@RequestParam(required = true)注解还是不能省略。
4.
这样swagger2与springboot就集成完毕了。
看下最终效果吧:
访问路径: http://localhost:8080/swagger-ui.html
调试:点击需要访问的api列表,点击try it out!按钮,表示 执行。