1、Swagger简介
根据在代码中使用自定义的注解来生成接口文档,这样做的好处是 在开发接口时可以通过swagger 将接口文档定义好提供给前端查询具体参数信息,同时也方便以后的维护。
当前项目配置好以后的Swagger原型:
2、Boot整合Swagger案例(复制可直接使用)
2.1、Pom文件依赖配置
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>BootSwagger</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>BootSwagger</name>
<description>BootSwagger</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--Swagger-UI API文档生产工具-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-annotations</artifactId>
<version>3.0.3</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
2.2、application.properties配置信息
#设置端口号
server.port=8088
#swagger配置
spring.mvc.pathmatch.matching-strategy=ant_path_matcher
2.3、在启动类同级别创建Config包
2.4、Swagger配置信息
2.4.1、配置跨域
package com.example.bootswagger.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class GlobalCorsConfig {
/**
* 跨域处理
*/
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
// 设置访问源地址
config.addAllowedOriginPattern("*");
// 设置访问源请求头
config.addAllowedHeader("*");
// 设置访问源请求方法
config.addAllowedMethod("*");
// 有效期 1800秒
config.setMaxAge(1800L);
// 添加映射路径,拦截一切请求
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
// 返回新的CorsFilter
return new CorsFilter(source);
}
}
2.4.2、Swagger自定义配置
package com.example.bootswagger.config;
import lombok.Builder;
import lombok.Data;
/**
* Swagger自定义配置
*/
@Data
@Builder
public class SwaggerProperties {
/**
* API文档生成基础路径
*/
private String apiBasePackage;
/**
* 是否要启用登录认证
*/
private boolean enableSecurity;
/**
* 文档标题
*/
private String title;
/**
* 文档描述
*/
private String description;
/**
* 文档版本
*/
private String version;
/**
* 文档联系人姓名
*/
private String contactName;
/**
* 文档联系人网址
*/
private String contactUrl;
/**
* 文档联系人邮箱
*/
private String contactEmail;
}
2.4.3、Swagger API文档相关配置(Swagger名称,控制层包扫描)
注意.apiBasePackage(“com.example.bootswagger.controller”)是用来设置你的Controller所在包路径!
package com.example.bootswagger.config;
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* Swagger API文档相关配置
*
* @author mac
*/
@Configuration
@EnableSwagger2
@EnableKnife4j
@Import(BeanValidatorPluginsConfiguration.class)
public class SwaggerConfig extends SuperSwaggerConfig {
@Override
public SwaggerProperties swaggerProperties() {
return SwaggerProperties.builder()
//设置Swagger扫描的Controller路径,只有扫描到了才会生成接口文档
.apiBasePackage("com.example.bootswagger.controller")
.title("swagger测试")
.description("后台接口文档")
.contactName("wranglings")
.version("1.0")
.enableSecurity(true)
.build();
}
}
2.4.4、Swagger基础配置
package com.example.bootswagger.config;
import org.springframework.context.annotation.Bean;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import java.util.Collections;
import java.util.List;
/**
* Swagger基础配置
* @author mac
*/
public abstract class SuperSwaggerConfig {
/**
* 自定义Swagger配置
*/
public abstract SwaggerProperties swaggerProperties();
@Bean
public Docket docket() {
SwaggerProperties swaggerProperties = swaggerProperties();
Docket docket = new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo(swaggerProperties))
.select()
.apis(RequestHandlerSelectors.basePackage(swaggerProperties.getApiBasePackage()))
.paths(PathSelectors.any())
.build();
if (swaggerProperties.isEnableSecurity()) {
docket.securitySchemes(Collections.singletonList(securitySchemes()))
.securityContexts(Collections.singletonList(securityContexts()));
}
return docket;
}
private ApiInfo apiInfo(SwaggerProperties swaggerProperties) {
return new ApiInfoBuilder()
.title(swaggerProperties.getTitle() + " 服务API接口文档")
.description(swaggerProperties.getDescription())
.version(swaggerProperties.getVersion())
.contact(new Contact(swaggerProperties.getContactName(), swaggerProperties.getContactUrl(), swaggerProperties.getContactEmail()))
.version(swaggerProperties.getVersion())
.build();
}
private ApiKey securitySchemes() {
//设置请求头信息
return new ApiKey("token", "accessToken", "header");
}
private SecurityContext securityContexts() {
return SecurityContext.builder()
.securityReferences(defaultAuth())
.operationSelector(operationContext -> true)
.build();
}
private List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("xxx", "描述信息");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return Collections.singletonList(new SecurityReference("Authorization", authorizationScopes));
}
}
2.4.5、创建测试VO 和 Controller
创建用户Vo
package com.example.bootswagger.pojo.vo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
@Data
@AllArgsConstructor
@NoArgsConstructor
@ApiModel("用户vo")
public class UserVo implements Serializable {
@ApiModelProperty(value = "用户id")
private Integer userId;
@ApiModelProperty(value = "用户名称")
private String userName;
@ApiModelProperty(value = "用户密码")
private String password;
}
创建Controller层
package com.example.bootswagger.controller;
import com.example.bootswagger.pojo.vo.UserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Api(tags = "用户信息")
@RestController
@RequestMapping("/user")
public class UserController {
@ApiOperation(value = "查询用户详细信息")
@GetMapping("/getInfo")
public UserVo getInfo(Integer userId){
UserVo userVo = new UserVo();
if(ObjectUtils.isNotEmpty(userId)){
userVo.setUserId(userId);
userVo.setUserName("admin");
userVo.setPassword("root");
}
return userVo;
}
}
2.4.6、启动Swagger,重点菜单说明
链接: http://localhost:8088/doc.html
主页
授权
文档管理
这里可以配置一些消息头和一些查询参数,可以添加多个
剩下的菜单就是读取的Controller的信息
这里是测试案例中配置的用户信息接口
3、Swagger常用注解说明
3.1、@ApiModel(“用户vo”)
@ApiModel注解,用来配置Swagger文档中返回的对象名称,常用在实体类中;
如下图:
3.2、@ApiModelProperty(value = “用户id”)
@ApiModelProperty,用来配置Swagger文档中返回的对象的属性名称,如上图!
用户id、用户名称这些都是通过该注解配置的。
3.3、@Api(tags = “用户信息”)
@Api(tags = “”),用来配置控制层,在Swagger文档的菜单项可以体现!如下图
文章来源:https://www.toymoban.com/news/detail-419066.html
3.4、@ApiOperation(value = “查询用户详细信息”)
@ApiOperation(value = “”),用来配置控制层中具体的方法,在Swagger文档的菜单项可以体现!如上图文章来源地址https://www.toymoban.com/news/detail-419066.html
到了这里,关于SpringBoot项目配置Swagger的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!