项目环境
Srping Boot版本
2.0.6.RELEASE
JDK版本
1.8
配置文件
配置Swagger,使用Swagger.java文件实现
Swagger.java
package com.xxx.xxx.xxx.config;
import com.google.common.base.Predicate;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMethod;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.ResponseMessageBuilder;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
import java.util.List;
import static com.google.common.base.Predicates.or;
import static springfox.documentation.builders.PathSelectors.regex;
/**
* SwaggerConfig
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
//@Value("${server.servlet-path}")
private String pathMapping;
private ApiInfo initApiInfo() {
ApiInfo apiInfo = new ApiInfo("这里是大标题",//大标题
initContextInfo(),//简单的描述
"1.0.0",//版本
"服务条款",
"后台开发团队",//作者
"The Apache License, Version 2.0",//链接显示文字
"http://www.baidu.com"//网站链接
);
return apiInfo;
}
private String initContextInfo() {
StringBuffer sb = new StringBuffer();
sb.append("REST API 设计在细节上有很多自己独特的需要注意的技巧,并且对开发人员在构架设计能力上比传统 API 有着更高的要求。")
.append("
")
.append("本文通过翔实的叙述和一系列的范例,从整体结构,到局部细节,分析和解读了为了提高易用性和高效性,REST API 设计应该注意哪些问题以及如何解决这些问题。");
return sb.toString();
}
@Bean
public Docket restfulApi() {
List responseMessageList = new ArrayList<>();
return new Docket(DocumentationType.SWAGGER_2)
.groupName("组名称")
// .genericModelSubstitutes(DeferredResult.class)
.genericModelSubstitutes(ResponseEntity.class)
.useDefaultResponseMessages(true)
.forCodeGeneration(false)
//.pathMapping(pathMapping) // base,最终调用接口后会和paths拼接在一起
//.pathMapping("api/v1") // base,最终调用接口后会和paths拼接在一起
.select()
//.paths(doFilteringRules())
// 配置扫描的接口包位置 .apis(RequestHandlerSelectors.basePackage("com.xxx.xxx.xxx.controller"))
.paths(PathSelectors.any())
.build()
.securitySchemes(Lists.newArrayList(apiKey()))
.apiInfo(initApiInfo());
}
private ApiKey apiKey() {
return new ApiKey("apikey", "Authentication", "header");
}
/**
* SecurityScheme 子类 BasicAuth OAuth ApiKey
* @return
*/
private SecurityScheme securitySchemes(){
// basicAuth SwaggerBootstrapUI支持的不好,使用swagger原生UI
return new BasicAuth("basicAuth");
}
/**
* 设置过滤规则
* 这里的过滤规则支持正则匹配
* @return
*/
private Predicate doFilteringRules() {
return or(
regex("/hello.*"),
regex("/vehicles.*")
);
}
}
这里配置了Swagger启动后的一些用户自定义的配置信息,接口所在的包位置及密钥信息。
本项目中需要配置的信息,防止被拦截而无法访问。
WebMvcConfig.java
package com.xxx.xxx.xxx.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextListener;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
//super.addResourceHandlers(registry);
}
@Bean
public RequestContextListener requestContextListenerBean() {
return new RequestContextListener();
}
}
配置对"swagger-ui.html"不作拦截,避免Swagger无法访问。
接下来是Pom文件的配置:
Pom.xml
io.springfox
springfox-swagger-ui
2.8.0
io.springfox
springfox-swagger2
2.8.0
com.github.xiaoymin
swagger-bootstrap-ui
1.9.6
这里选用github开源的组件进行实现。
Controller接口层
Controller需要定义成与上述路径一致的位置,在Controller类上使用@Api注解,在具体的接口方法上使用@ApiOperation,需要对参数另外说明的需要配合@ApiImplicitParams注解进行使用。
UserController.java
package com.xxx.xxx.xxx.controller;
import com.bjbde.admin.common.annotation.Log;
import com.bjbde.admin.common.controller.BaseController;
import com.bjbde.admin.common.domain.QueryRequest;
import com.bjbde.admin.common.exception.FebsException;
import com.bjbde.admin.common.utils.MD5Util;
import com.bjbde.admin.system.domain.User;
import com.bjbde.admin.system.domain.UserConfig;
import com.bjbde.admin.system.service.UserConfigService;
import com.bjbde.admin.system.service.UserService;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.wuwenze.poi.ExcelKit;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.List;
import java.util.Map;
@Api(value = "API - UserController", tags = "运行管理系统-安全管理-用户管理")
@Slf4j
@Validated
@RestController
@RequestMapping("user")
public class UserController extends BaseController {
private String message;
@Autowired
private UserService userService;
@Autowired
private UserConfigService userConfigService;
@ApiOperation(value = "检查候选用户名是否可用(唯一)", notes = "检查候选用户名是否可用(唯一)。", response = String.class, authorizations = {@Authorization(value="apikey")})
@ApiImplicitParams({
@ApiImplicitParam(name = "username", value = "候选用户名", required = true, dataType = "string", paramType = "path")
})
@GetMapping("check/{username}")
public boolean checkUserName(@NotBlank(message = "{required}") @PathVariable String username) {
return this.userService.findByName(username) == null;
}
}
实体类
实体类上需要对实体类加注解@Api,以便注解实体类;属性上需要加注解@ApiModelProperty属性
User.java
package com.xxx.xxx.xxx.domain;
import com.bjbde.admin.common.converter.TimeConverter;
import com.bjbde.admin.common.domain.RegexpConstant;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.wuwenze.poi.annotation.Excel;
import com.wuwenze.poi.annotation.ExcelField;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.Date;
@Data
@ApiModel("用户")
@TableName("user")
@Excel("用户信息表")
public class User implements Serializable {
private static final long serialVersionUID = -4852732617765810959L;
@ApiModelProperty(value = "用户编号")
@TableId(value = "USER_ID", type = IdType.AUTO)
private Long userId;
@ApiModelProperty(value = "用户名")
@Size(min = 4, max = 20, message = "{range}")
@ExcelField(value = "用户名")
private String username;
@ApiModelProperty(value = "密码")
private String password;
@ApiModelProperty(value = "姓名")
@NotBlank(message = "{required}")
@ExcelField(value = "姓名")
private String fullName;
@ApiModelProperty(value = "部门编号")
private Long deptId;
@ApiModelProperty(value = "部门")
@ExcelField(value = "部门")
private transient String deptName;
}
至此,Swagger注解配置部分基本完成。
访问地址
http://{IP}:{Port}/swagger-ui.html
得到文档页面如下