1.简介
Swagger是一个规范和完整的框架,用于生成、描述、调用和可视化RESTful风格的Web服务。
2.pom配置swagger依赖
<!--swagger图形化接口-->
<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>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.8.7</version>
</dependency>
3. 创建swagger配置类
package com.**.dfp.rtsync.controller;
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.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* Description
*
* @author Bob
* @date 2020/8/31
**/
@Configuration
@EnableSwagger2
@ConditionalOnProperty(prefix = "mconfig", name = "swagger-ui-open", havingValue = "true")
public class Swagger2Config {
/**
* @description 创建API应用
* apiInfo() 增加API相关信息
* 通过select()函数返回一个ApiSelectorBuilder实例,用来控制哪些接口暴露给Swagger来展现,
* 本例采用指定扫描的包路径来定义指定要建立API的目录。
* @author Bob
* @date 2020/8/31
*/
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.**.dfp.rtsync.controller"))
.paths(PathSelectors.any())
.build();
}
/**
* @description 创建该API的基本信息(这些基本信息会展现在文档页面中)
* 访问地址:http://项目实际地址/swagger-ui.html
* @author Bob
* @date 2020/8/31
*/
public ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("数据流平台接口文档")
.description("使用技巧:1接口文档,仔细阅读请求参数、响应参数的说明;2在线调试:利用此功能进行在线调试;")
.contact("dfp")
.version("1.0")
.build();
}
}
@Configuration
代表当前是配置文件@EnableSwagger2
代表开启swagger2@ConditionalOnProperty(prefix = "mconfig", name = "swagger-ui-open", havingValue = "true")
是控制当前的config是否生效,其中的参数对应着我的application.yml
文件,如果我的参数为非true,那么swagger则关闭
application.properties文件添加mconfig.swagger-ui-open=true表示开启swagger,生产设为false
3.对接口和实体类添加注释。常用注解如下:
@Api()用于类;
标识这个类是swagger的资源
tags–表示分组说明标签
@ApiOperation()用于方法;
表示一个http请求的操作
value用于方法描述
notes用于提示内容
@ApiModel()用于实体类
表示对类进行说明,用于参数用实体类接收
value–表示对象名
description–描述
@ApiModelProperty()用于实体类字段
表示对model属性的说明或者数据操作更改
value–字段说明
name–重写属性名字
dataType–重写属性类型
required–是否必填
example–举例说明
hidden–隐藏
@ApiImplicitParam() 用于 controller 方法
表示单独的请求参数
name–参数ming
value–参数说明
dataType–数据类型
paramType–参数类型
example–举例说明
@ApiImplicitParams() 用于 controller 方法,包含多个 @ApiImplicitParam
@ApiIgnore()用于类或者方法上,可以不被swagger显示在页面上
说明:简单的标记只需要@Api(tags="") 和 @ApiOperation(value="",notes="")
更多关于 注解用法可以参考https://github.com/swagger-api/swagger-core/wiki/Annotations
@RestController
@RequestMapping("/task")
@Slf4j
@Api(tags = "任务管理")
public class TaskController extends BaseController {
@PostMapping("/save")
@ApiOperation("新增/修改任务")
public RestResponse<Boolean> save(@RequestBody DfpTask dfpTask) {
********
}
}
@Data
@TableName("dfp_task")
@ApiModel("任务")
public class DfpTask extends BaseModel {
private static final long serialVersionUID = 6374461866635509474L;
/**
* 任务名称
*/
@ApiModelProperty(value = "任务名称", dataType = "String", required = true, example = "会员实时抽数任务")
private String taskName;
********
}
4. 启动测试
在浏览器中输入 http://localhost:8080/swagger-ui.html
会展示出所有的controller以及models
5.采坑
5.1 所有controller都出不来
解决:查看swagger配置类是不是在controller包下面,或者其包路径跟controller包平级
或者配置类修改apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) 为 apis(RequestHandlerSelectors.basePackage("com.****.controller"))
5.2 controller可以看到,但是点开都是空
解决:F12看下页面是否报错,个人项目中集成了springsecurity,报认证失败。
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Qualifier("userDetailsServiceImpl")
@Autowired
private UserDetailsService userDetailsService;
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
// 使用自定义身份验证组件
auth.authenticationProvider(new JwtAuthenticationProvider(userDetailsService));
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// 禁用 csrf, 由于使用的是JWT,我们这里不需要csrf
http.cors().and().csrf().disable()
.authorizeRequests()
// 跨域预检请求
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
// 首页和登录页面
.antMatchers("/").permitAll()
.antMatchers("/login").permitAll()
// swagger
.antMatchers("/swagger-ui.html").permitAll()
.antMatchers("/swagger-resources/**").permitAll()
.antMatchers("/images/**").permitAll()
.antMatchers("/webjars/**").permitAll()
.antMatchers("/v2/api-docs").permitAll()
.antMatchers("/configuration/ui").permitAll()
.antMatchers("/configuration/security").permitAll()
// 验证码
.antMatchers("/captcha.jpg**").permitAll()
// 其他所有请求需要身份认证
.anyRequest().authenticated();
// 退出登录处理器
http.logout().logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler());
// token验证过滤器
http.addFilterBefore(new JwtAuthenticationFilter(authenticationManager()), UsernamePasswordAuthenticationFilter.class);
}
@Bean
@Override
public AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
}
}
参考:https://www.cnblogs.com/zhaopengcheng/p/8583659.html
https://www.cnblogs.com/zhaopengcheng/p/8583659.html
https://www.jianshu.com/p/56aaa5b1355d
https://www.cnblogs.com/softidea/p/6295115.html