springboot集成springSwagger生成接口文档
1. 首先引入pom.xml依赖
<!-- Swagger API文档 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
<exclusions>
<exclusion>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
</exclusion>
<exclusion>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.9.6</version>
</dependency>
<!-- # 增加两个配置解决 NumberFormatException -->
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>1.5.22</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
<version>1.5.22</version>
</dependency>
<!-- Swagger API文档 -->
2. 编写spring swagger 的配置文件
import com.github.xiaoymin.swaggerbootstrapui.annotations.EnableSwaggerBootstrapUI;
import com.google.common.collect.Lists;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMethod;
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.builders.ResponseMessageBuilder;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* @Decription SWAGGER
*/
@Slf4j
@Configuration
@EnableSwagger2
@EnableSwaggerBootstrapUI
@ConditionalOnProperty(name = "swagger.enable", havingValue = "true")
public class Swagger2Config implements WebMvcConfigurer {
/**
* swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包等等
*
* @return Docket
*/
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//此包路径下的类,才生成接口文档
.apis(RequestHandlerSelectors.basePackage("com.el.springboot.controller")) //注意修改这里为自己的
//加了ApiOperation注解的类,才生成接口文档
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build()
// 开启 URL 模板缓存
.enableUrlTemplating(true)
// 开启 Swagger UI
.enable(true)
// 设置请求响应信息
.useDefaultResponseMessages(false)
.globalResponseMessage(RequestMethod.POST, Lists.newArrayList(
new ResponseMessageBuilder().code(200).message("请求成功").build(),
new ResponseMessageBuilder().code(400).message("请求参数错误").build(),
new ResponseMessageBuilder().code(401).message("未授权").build(),
new ResponseMessageBuilder().code(403).message("禁止访问").build(),
new ResponseMessageBuilder().code(404).message("请求路径不存在").build(),
new ResponseMessageBuilder().code(500).message("服务器内部错误").build()
));
}
/**
* api文档的详细信息函数,注意这里的注解引用的是哪个
*
* @return
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
// //大标题
.title("xxx项目-xxx管理-API接口文档")
// 版本号
.version("1.0")
// 描述
.description("xxxAPI接口")
// 作者
.contact("xxx")
.license("The Apache License, Version 2.0")
.licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
.build();
}
}
3. 配置WebMvcConfigurer
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
/**
* @author el
* 2023/5/9
*/
@Configuration
public class WebMvcConfigurer extends WebMvcConfigurationSupport {
/**
* 发现如果继承了WebMvcConfigurationSupport,则在yml中配置的相关内容会失效。 需要重新指定静态资源
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations(
"classpath:/static/");
registry.addResourceHandler("swagger-ui.html", "doc.html").addResourceLocations(
"classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations(
"classpath:/META-INF/resources/webjars/");
super.addResourceHandlers(registry);
}
}
4. application.yml配置
server:
port: 9090 #springboot启动端口号
#enable 配置swagger
swagger:
enable: true
5. 访问地址
http://localhost:9090/doc.html
6. Swagger常用注解
注解 | 作用 |
---|---|
@Api | 用在类上,说明该类的作用。 |
@ApiOperation | 用在方法上,说明方法的作用。 |
@ApiParam | 用在参数上,描述参数信息。 |
@ApiModel | 用在实体类上,给实体类添加注释。 |
@ApiModelProperty | 用在实体类属性上,给属性添加注释。 |
7. 代码示例
@RestController
@RequestMapping("/users")
@Api(tags = "用户管理")
public class UserController {
@Autowired
private UserService userService;
@PostMapping
@ApiOperation("添加用户")
public Result addUser(@RequestBody @ApiParam("用户信息") User user) {
userService.addUser(user);
return Result.success();
}
@GetMapping("/{id}")
@ApiOperation("根据ID查询用户")
public Result<User> getUserById(@PathVariable("id") @ApiParam("用户ID") Long id) {
User user = userService.getUserById(id);
return Result.success(user);
}
@GetMapping
@ApiOperation("查询用户列表")
public Result<List<User>> getUserList() {
List<User> userList = userService.getUserList();
return Result.success(userList);
}
@PutMapping("/{id}")
@ApiOperation("更新用户信息")
public Result updateUser(@PathVariable("id") @ApiParam("用户ID") Long id, @RequestBody @ApiParam("用户信息") User user) {
userService.updateUser(id, user);
return Result.success();
}
@DeleteMapping("/{id}")
@ApiOperation("删除用户")
public Result deleteUser(@PathVariable("id") @ApiParam("用户ID") Long id) {
userService.deleteUser(id);
return Result.success();
}
}
8. 详细使用
使用@Api注解可以描述API文档的基本信息,如下所示:
@Api(value = "用户管理接口", tags = {"用户管理"})
@RestController
@RequestMapping("/user")
public class UserController {
...
}
使用@ApiOperation注解可以描述某个接口的基本信息,如下所示:
@ApiOperation(value = "查询用户信息", notes = "根据用户ID查询用户信息")
@GetMapping("/{id}")
public User getUserById(@PathVariable Integer id) {
return userService.getUserById(id);
}
使用@ApiParam注解可以描述某个接口的参数信息,如下所示:
@ApiOperation(value = "添加用户", notes = "添加用户信息")
@PostMapping("/")
public void addUser(@ApiParam(name = "user", value = "用户信息", required = true) @RequestBody User user) {
userService.addUser(user);
}
使用@ApiModel和@ApiModelProperty注解可以描述数据模型及其属性信息,如下所示:
@ApiModel(description = "用户模型")
public class User {
@ApiModelProperty(value = "用户ID", example = "1")
private Integer id;
@ApiModelProperty(value = "用户名", example = "张三")
private String name;
@ApiModelProperty(value = "用户年龄", example = "20")
private Integer age;
...
}