-----Swagger2生成API文档规则
2020.08.27
参考博客:https://www.cnblogs.com/ynyhl/p/13322432.html
<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>
@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("yunqing", "", "yunqing****@gmail.com");
return new ApiInfoBuilder()
.title("SwaggerUI演示")
.description("接口文档,描述词省略200字")
.contact(contact)
.version("1.0")
.build();
}
/**
* 配置swagger2的静态资源路径
* @param registry
*/
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
// 解决静态资源无法访问
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/static/");
// 解决swagger无法访问
registry.addResourceHandler("/swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
// 解决swagger的js文件无法访问
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
/**
* 给API文档接口添加安全认证
*/
private List<ApiKey> securitySchemes() {
List<ApiKey> apiKeys = new ArrayList<>();
apiKeys.add(new ApiKey("Authorization", "Authorization", "header"));
return apiKeys;
}
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("Authorization", authorizationScopes));
return securityReferences;
}
}
filterChainDefinitionMap.put("/swagger-ui.html**", "anon");
filterChainDefinitionMap.put("/v2/api-docs", "anon");
filterChainDefinitionMap.put("/swagger-resources/**", "anon");
filterChainDefinitionMap.put("/webjars/**", "anon");
eg.
@Api(tags = "账户相关模块")
@RestController
@RequestMapping("/api/account")
public class AccountController{
// TODO
}
eg.
@ApiOperation(value = "修改密码", notes = "方法的备注说明,如果有可以写在这里")
@PostMapping("/changepass")
public AjaxResult changePassword(@AutosetParam SessionInfo sessionInfo, @RequestBody @Valid PasswordModel passwordModel) {
// TODO
}
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
}
@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
}
eg. 一个POJO类
@ApiModel("修改密码所需参数封装类")
public class PasswordModel
{
@ApiModelProperty("账户Id")
private String accountId;
//TODO
}
使用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 本地不能一直跑
原文:https://www.cnblogs.com/hualingnan/p/bootSwagger2.html