配置依赖的包
<properties>
<swagger.version>2.9.2</swagger.version>
</properties>
<dependencies>
<!-- 将swagger整合到spring boot项目中 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
</dependencies>
swagger配置文件
@Configuration
@EnableSwagger2
//@ComponentScan(basePackages = "com.springboot.demo.controller")//配置扫描的基础包
public class SwaggerConfiguration {
/**
* swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包等等
* 在构建文档的时候 只显示添加了@Api注解的类
* @return
*/
@Bean //作为bean纳入spring容器
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.paths(PathSelectors.any())
.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))//只显示添加了@Api注解的类
.build();
}
/**
* 构建 api文档的详细信息函数,注意这里的注解引用的是哪个
* @return
*/
private ApiInfo apiInfo(){
return new ApiInfoBuilder()
.title("API接口文档")
.description("API接口文档,及相关接口的说明")
.version("1.0.0")
.build();
}
}
效果如下
输入http://localhost:端口号/swagger-ui.html
效果如下对于接口的配置–基于注解
@Api()用于类:表示标识这个类是swagger的资源 不标识也无所谓
@Api(value=“用户controller”,tags={“用户操作接口”})
@ApiOperation()用于方法; 表示一个http请求的操作 不标识也无所谓
@ApiOperation(value=“根据用户编号获取用户姓名”, notes=“test: 仅1和2有正确返回”)
@ApiParam:单个参数描述
@ApiModel:用对象来接收参数
@ApiModelProperty:用对象接收参数时,描述对象的一个字段
@ApiResponse:HTTP响应其中1个描述
@ApiResponses:HTTP响应整体描述
@ApiIgnore:使用该注解忽略这个API
@ApiError :发生错误返回的信息
@ApiImplicitParam() 用于方法 表示单独的请求参数
@ApiImplicitParam(paramType=“query”, name = “userNumber”, value = “用户编号”, required = true, dataType = “Integer”)
@ApiImplicitParams() 用于方法,包含多个 @ApiImplicitParam
@ApiImplicitParams({
@ApiImplicitParam(paramType="query", name = "userId", value = "用户ID", required = true, dataType = "Integer"),
@ApiImplicitParam(paramType="query", name = "password", value = "旧密码", required = true, dataType = "String"),
@ApiImplicitParam(paramType="query", name = "newPassword", value = "新密码", required = true, dataType = "String")
})
样例&效果
@RestController
@RequestMapping("/v1/test")
@Api(value = "HelloSpringBoot", tags = "测试", description = "我看行")
public class HelloSpringBoot {
@Autowired
HelloService helloService;
@SysLog("hello 测试")
@GetMapping(value = "/hello")
public String hello(@RequestParam("str") String str){
return helloService.hello(str);
}
}
以上为swagger初步接入
swagger拓展用法详见