springboot集成swagger
如何使用swagger生成Web API
1.在pom文件中添加如下依赖
<!-- swagger2 依赖配置-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
</dependency>
2.创建swagger配置类
package com.yangjunbo.helloword.properties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class Swagger2Config implements WebMvcConfigurer {
//指定需要扫描的包路径
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.yangjunbo.helloword.controller"))
.paths(PathSelectors.any())
.build();
}
//编辑网站信息,如网站的标题、网站的描述、使用的协议等。
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Spring Boot中使用Swagger2构建RESTful APIs")
.description("Spring Boot相关文章请关注:https://www.cnblogs.com/zhangweizhong")
.termsOfServiceUrl("https://www.cnblogs.com/zhangweizhong")
.contact("架构师精进")
.version("1.0")
.build();
}
/**
* swagger增加url映射
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
3.在controller类上添加注解说明
package com.yangjunbo.helloword.controller;
import com.yangjunbo.helloword.common.JSONResult;
import com.yangjunbo.helloword.pojo.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@Api(tags={"用户接口"})
@RestController
public class UserController {
@ApiOperation(value = "创建用户",notes="根据user对象创建用户")
@PostMapping(value = "user")
public JSONResult save(@RequestBody User user){
System.out.println("用户创建成功"+user.getName());
return JSONResult.ok(201,"用户创建成功");
}
@ApiOperation(value = "更新用户信息",notes="根据ID来指定更新对象,并根据传过来的user信息来更新用户信息")
@PutMapping(value = "user")
public JSONResult update(@RequestBody User user) {
System.out.println("用户修改成功:"+user.getName());
return JSONResult.ok(203,"用户修改成功");
}
@ApiOperation(value = "删除用户信息",notes="根据URL中的ID指定删除对象")
@ApiImplicitParam(name="userId",value = "用户ID",required = true,dataType = "String",paramType = "query")
@DeleteMapping("user/{userId}")
public JSONResult delete(@PathVariable String userId) {
System.out.println("用户删除成功:"+userId);
return JSONResult.ok(204,"用户删除成功");
}
@ApiOperation(value = "获取用户信息",notes="根据URL中的ID获取指定对象")
@ApiImplicitParam(name="userId",value = "用户ID",required = true,dataType = "String",paramType = "query")
@GetMapping("user/{userId}")
public JSONResult queryUserById(@PathVariable String userId) {
User user =new User();
user.setName("weiz");
user.setAge(20);
System.out.println("获取用户成功:"+userId);
return JSONResult.ok(200,"获取用户成功",user);
}
}
4.启动项目,访问swagger主页,http://localhost:8080/swagger-ui.html
5.使用 try it out 测试接口
6.为所有API添加token参数
修改上面的swagger配置类中的creatRestApi方法,如下
@Bean
public Docket createRestApi() {
//添加请求参数,这里把token作为请求头参数传入后端
ParameterBuilder parameterBuilder = new ParameterBuilder();
List<Parameter> parameterList = new ArrayList<Parameter>();
parameterBuilder.name("token").description("token令牌").modelRef(new ModelRef("String")).parameterType("header")
.required(false).build();
parameterList.add(parameterBuilder.build());
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.yangjunbo.helloword.controller"))
.paths(PathSelectors.any())
.build()
.globalOperationParameters(parameterList);
}
重新启动项目,再次访问swagger主页,发现API已经支持添加token参数了,swagger会自动把token参数放到请求头中
7.swagger常用注解
参考书籍:springboot从入门到实战-章为忠编著