首页 > 编程语言 > 详细

SpringBoot集成Swagger2.0

时间:2020-09-14 23:33:16      阅读:108      评论:0      收藏:0      [点我收藏+]
api-node

SpringBoot接口文档

-----Swagger2生成API文档规则

2020.08.27

参考博客:https://www.cnblogs.com/ynyhl/p/13322432.html

配置规则

  1. 导包
<dependency>    
	<groupId>io.springfox</groupId>    				
    <artifactId>springfox-boot-starter</artifactId>    	
    <version>3.0.0</version>
</dependency>
<dependency>    
    <groupId>io.springfox</groupId>    		
	<artifactId>springfox-swagger2</artifactId>   		 
    <version>3.0.0</version>
</dependency>
  1. 配置类
@Configuration
@EnableSwagger2
public class SwaggerConfig extends WebMvcConfigurationSupport {
    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //为当前包下controller生成API文档
                .apis(RequestHandlerSelectors.basePackage("com.troila"))
                //为有@Api注解的Controller生成API文档
                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
                //为有@ApiOperation注解的方法生成API文档
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                //为任何接口生成API文档
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
                //添加登录认证
                .securitySchemes(securitySchemes())
                .securityContexts(securityContexts());
    }
private ApiInfo apiInfo() {
    Contact contact = new Contact(&quot;yunqing&quot;, &quot;&quot;, &quot;yunqing****@gmail.com&quot;);
    return new ApiInfoBuilder()
            .title(&quot;SwaggerUI演示&quot;)
            .description(&quot;接口文档,描述词省略200字&quot;)
            .contact(contact)
            .version(&quot;1.0&quot;)
            .build();
}

/**
 * 配置swagger2的静态资源路径
 * @param registry
 */
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
    // 解决静态资源无法访问
    registry.addResourceHandler(&quot;/**&quot;)
            .addResourceLocations(&quot;classpath:/static/&quot;);
    // 解决swagger无法访问
    registry.addResourceHandler(&quot;/swagger-ui.html&quot;)
            .addResourceLocations(&quot;classpath:/META-INF/resources/&quot;);
    // 解决swagger的js文件无法访问
    registry.addResourceHandler(&quot;/webjars/**&quot;)
            .addResourceLocations(&quot;classpath:/META-INF/resources/webjars/&quot;);
}


/**
 * 给API文档接口添加安全认证
 */
private List&lt;ApiKey&gt; securitySchemes() {
    List&lt;ApiKey&gt; apiKeys = new ArrayList&lt;&gt;();
    apiKeys.add(new ApiKey(&quot;Authorization&quot;, &quot;Authorization&quot;, &quot;header&quot;));
    return apiKeys;
}

private List&lt;SecurityContext&gt; securityContexts() {
    List&lt;SecurityContext&gt; securityContexts = new ArrayList&lt;&gt;();
    securityContexts.add(SecurityContext.builder()
            .securityReferences(defaultAuth())
            .forPaths(PathSelectors.regex(&quot;^(?!auth).*$&quot;)).build());
    return securityContexts;
}

private List&lt;SecurityReference&gt; defaultAuth() {
    AuthorizationScope authorizationScope = new AuthorizationScope(&quot;global&quot;, &quot;accessEverything&quot;);
    AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
    authorizationScopes[0] = authorizationScope;
    List&lt;SecurityReference&gt; securityReferences = new ArrayList&lt;&gt;();
    securityReferences.add(new SecurityReference(&quot;Authorization&quot;, authorizationScopes));
    return securityReferences;
}

}

  1. ShiroConfig或者SecurityConfig放置swagger2配置类资源
filterChainDefinitionMap.put("/swagger-ui.html**", "anon");
filterChainDefinitionMap.put("/v2/api-docs", "anon");
filterChainDefinitionMap.put("/swagger-resources/**", "anon");
filterChainDefinitionMap.put("/webjars/**", "anon"); 

注解规则

  1. @Api : 请求类 与Controller放在一起 说明类的作用

eg.

@Api(tags = "账户相关模块")
@RestController
@RequestMapping("/api/account")
public class AccountController{
    // TODO 
}
  1. @ApiOperation 请求方法说明

eg.

@ApiOperation(value = "修改密码", notes = "方法的备注说明,如果有可以写在这里")
@PostMapping("/changepass")
	public AjaxResult changePassword(@AutosetParam SessionInfo sessionInfo, @RequestBody @Valid PasswordModel passwordModel) {
    // TODO
 }
  1. @ApiImplicitParams、@ApiImplicitParam:方法参数的说明

eg.多参数

@ApiOperation(value="用户登录",notes="随边说点啥")
@ApiImplicitParams({
        @ApiImplicitParam(name="mobile",value="手机号",required=true,paramType="form"),
        @ApiImplicitParam(name="password",value="密码",required=true,paramType="form"),
        @ApiImplicitParam(name="age",value="年龄",required=true,paramType="form",dataType="Integer")
})
@PostMapping("/login")
public AjaxResult login(@RequestParam String mobile, @RequestParam String password,
                        @RequestParam Integer age){
    //TODO
    return AjaxResult.OK();
}

eg.单参数

@ApiOperation("根据部门Id删除")
@ApiImplicitParam(name="depId",value="部门id",required=true,paramType="query")
@GetMapping("/delete")
public AjaxResult delete(String depId) {
    //TODO
}
  1. @ApiResponses、@ApiResponse:方法返回值的说明
@ApiOperation(value = "修改密码", notes = "方法的备注说明,如果有可以写在这里")
@ApiResponses({
        @ApiResponse(code = 400, message = "请求参数没填好"),
        @ApiResponse(code = 404, message = "请求路径找不到")
})
@PostMapping("/changepass")
public AjaxResult changePassword(@AutosetParam SessionInfo sessionInfo,
        @RequestBody @Valid PasswordModel passwordModel) {
    //TODO
}
  1. @ApiModel:用于JavaBean上面,表示一个JavaBean
  2. @ApiModelProperty:用在JavaBean的属性上面,说明属性的含义

eg. 一个POJO类

@ApiModel("修改密码所需参数封装类")
public class PasswordModel
{
    @ApiModelProperty("账户Id")
    private String accountId;
//TODO
}

 

关于Swagger2 @ApiModel的一个坑

使用swagger的 @ApiModel注解的时候有个坑 就是必须在controller 使用 @RequestBody 注解 否则无法显示models

import io.swagger.v3.oas.annotations.parameters.RequestBody;

而且不报错,此时swagger就和 spring 耦合了,而且问题难以排查,

1、@requestBody注解常用来处理content-type不是默认的application/x-www-form-urlcoded编码的内容,比如说:application/json或者是application/xml等。一般情况下来说常用其来处理application/json类型。

2、通过@requestBody可以将请求体中的JSON字符串绑定到相应的bean上,当然,也可以将其分别绑定到对应的字符串上。

3 springBoot 中 使用@requestBody注解的话, 前端传递参数时需要JSON格式的参数,而且Content-Type为:application/json;charset=UTF-8 格式

@RequestBody的使用需要加载MappingJackson2HttpMessageConverter,但是SpringBoot的官方文档提到,这个是默认已经加载的了

没好啊....

彩蛋

将Swagger文档导入postman

postman-->import-->import from link

把公网ip导入 ok 本地不能一直跑

SpringBoot集成Swagger2.0

原文:https://www.cnblogs.com/hualingnan/p/bootSwagger2.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!