springboot整合swagger2
一)、配置
1、pom.xml中添加依赖,推荐使用2.9.2版本,会出现的问题可查看该文档:
swagger2【Parameter 0 of method linkDiscoverers in org.springframework.hateoas.config.】
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
2、application.yml中配置swagger2是否开启
备注:Swagger一般用于开发和测试环境,因为项目未区分生产、开发、测试配置,由application.yml统一配置,所以配置如下;若有环境区分,请忽略当前配置
hxiot:
swagger2:
enable: true
3、编写SwaggerConfig
package com.hxecm.config;
import io.swagger.annotations.ApiOperation;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
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.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
import java.util.List;
@Configuration
@EnableSwagger2
@ConditionalOnProperty(name = "hxiot.swagger2.enable", havingValue = "true")
public class SwaggerConfig {
@Bean
public Docket createRestAPi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build()
.securitySchemes(securitySchemes())
.securityContexts(securityContexts())
;
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("智能电厂物联网管控平台API文档")
.description("接口文档详情信息")
.version("1.0")
.contact(new Contact("", "", ""))
.license("")
.licenseUrl("")
.build();
}
private List<ApiKey> securitySchemes() {
List<ApiKey> apiKeyList = new ArrayList<>();
apiKeyList.add(new ApiKey("token", "Authorization", "header"));
return apiKeyList;
}
private List<SecurityContext> securityContexts() {
List<SecurityContext> securityContexts = new ArrayList<>();
securityContexts.add(
SecurityContext.builder()
.securityReferences(defaultAuth())
.forPaths(PathSelectors.regex("^(?!auth).*$"))
.build());
return securityContexts;
}
private List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
List<SecurityReference> securityReferences = new ArrayList<>();
securityReferences.add(new SecurityReference("token", authorizationScopes));
return securityReferences;
}
}
4、编写SecurityConfig
.antMatchers(
DataInitLoad.VIRTUAL_PATH + "/**",
"/webSocketServer/**",
"/swagger**/**",
"/swagger-ui.html",
"/swagger-resources/**",
"/webjars/**",
"/v2/**"// swagger
).permitAll()
5、编写WebMvcConfig
registry.addResourceHandler("swagger-ui.html").addResourceLocations(
"classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations(
"classpath:/META-INF/resources/webjars/");
6、重启服务,访问 http://localhost:8989/hexin/swagger-ui.html 出现以下页面表示启动成功
![在这里插入图片描述](https://img-blog.csdnimg.cn/8ccb626a82204b6f9529e7a912ca0652.png#pic_center)
二)、使用
1、接口
@RestController
@RequestMapping("/api/chemicalOilSupervision")
@RequiredArgsConstructor
@Api(tags = "油质监督管理模块")
public class ChemicalOilSupervisionController {
private final ChemicalOilSupervisionService chemicalOilSupervisionService;
@PostMapping("/uploadFile")
@ApiOperation("文件上传接口")
@ApiImplicitParam(name = "file", value = "文件", required = true)
public ResultData<? extends Object> uploadFile(@RequestParam("file") MultipartFile file) {
try {
FileResult fileResult = FileTools.uploadFile(file, "/" + HttpUtils.getCompanyId() + UploadConstants.CHEMICAL_OIL_SUPERVISION_PATH);
return new ResultData<>(fileResult.getCode(), fileResult.getMsg(), fileResult);
} catch (Exception e) {
e.printStackTrace();
return ResultData.exception();
}
}
@Transactional
@PostMapping("/insert")
@ApiOperation("保存接口")
public ResultData<? extends Object> insert(@RequestBody ChemicalOilSupervision chemicalOilSupervision) {
chemicalOilSupervision.setCompanyId(HttpUtils.getCompanyId());
return ResponseUtils.getResultData(
chemicalOilSupervisionService.insert(chemicalOilSupervision),
ResultData.Msg.MSG_ADD_SUCCESS,
ResultData.Code.CODE_ADD_ERROR,
ResultData.Msg.MSG_ADD_ERROR);
}
}
2、实体类
@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
@ToString
@ApiModel(description = "油质监督管理表实体类")
public class ChemicalOilSupervision implements Serializable {
private static final long serialVersionUID = -62241107545374991L;
@ApiModelProperty(value = "id")
private Long id;
@ApiModelProperty(value = "公司ID,不需要传递该参数")
private Long companyId = HttpUtils.getCompanyId();
@ApiModelProperty(value = "文件名称", required = true)
private String fileName;
}
三)、遇到的问题
1、项目中配置了springsecurity
springsecurity配置中添加以下代码,表示以下路径放开,不拦截
.antMatchers("/swagger-ui.html")
.permitAll()
.antMatchers("/v2/**")
.permitAll()
.antMatchers("/swagger-resources/**")
.permitAll()
.antMatchers("/webjars/**")
.permitAll()
2、项目中若配置了WebMvcConfigurer
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// swagger2
registry.addResourceHandler("swagger-ui.html").addResourceLocations(
"classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations(
"classpath:/META-INF/resources/webjars/");
}
3、swagger只在开发和测试环境中使用
方式一:
1、application.yml中配置
hxiot:
swagger2:
# 是否开启swagger2 开启为true,关闭为false
enable: true
2、在Swagger2Config上使用@ ConditionalOnProperty注解,@ConditionalOnProperty(name = "hxiot.swagger2.enable", havingValue = "true")表示配置文件中如果swagger.enable =true表示开启。所以只需要在开发环境的配置文件配置为true,生产环境配置为false即可。
方式二:
在Swagger2Config上使用@Profile注解标识,@Profile({"dev","test"})表示在dev和test环境才能访问swagger-ui.html,prod环境下访问不了
4、相关注解
1、请求类的描述
2、方法和方法参数的描述
注解 | 说明 |
---|
@ApiOperation | 方法的说明 |
@ApiImplicitParams | 方法参数的说明; |
@ApiImplicitParam | 用于指定单个参数的说明。 |
3、方法的响应状态的描述
注解 | 说明 |
---|
@ApiResponses | 方法返回值的说明 ; |
@ApiResponse | 用于指定单个参数的说明。 |
4、对象的描述
注解 | 说明 |
---|
@ApiModel | 用在JavaBean类上,说明JavaBean的 整体用途 |
@ApiResponses | 方法返回值的说明 ; |
@ApiResponse | 用于指定单个参数的说明。 |
4、对象的描述
注解 | 说明 |
---|
@ApiModel | 用在JavaBean类上,说明JavaBean的 整体用途 |
@ApiModelProperty | 用在JavaBean类的属性上面,说明此属性的的含议 |