<dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-swagger2artifactId>
<version>2.6.1version>(
${springfox.version}) dependency>
<dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-swagger-uiartifactId>
<version>2.6.1version>
dependency>
import com.google.common.base.Predicates;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
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;
/**
* @desc: Swagger
* @version:1.0.0
* @author:BG347670
* @Date:2018/5/23
*/
@Configuration //相当于配置信息注解, 等价于XML中配置beans
@EnableSwagger2 //表示swagger的配置信息
public class SwaggerConfig {
private final static String AUTHORIZATION_HEADER = "Authorization";
private final static String HEADER = "header";
private final static String CONTENT_TYPE = "Content-Type";
@Bean
@ConditionalOnMissingBean
/**
@Conditional(MyCondition.class)
这句代码可以标注在类上面,表示该类下面的所有@Bean都会启用配置
也可以标注在方法上面,只是对该方法启用配置
除了自己自定义Condition之外,Spring还提供了很多Condition给我们用
@ConditionalOnBean(仅仅在当前上下文中存在某个对象时,才会实例化一个Bean)
@ConditionalOnClass(某个class位于类路径上,才会实例化一个Bean)
@ConditionalOnExpression(当表达式为true的时候,才会实例化一个Bean)
@ConditionalOnMissingBean(仅仅在当前上下文中不存在某个对象时,才会实例化一个Bean)
@ConditionalOnMissingClass(某个class类路径上不存在的时候,才会实例化一个Bean)
@ConditionalOnNotWebApplication(不是web应用)
以上是一些常用的注解,其实就是条件判断,如果为true了就创建Bean,为false就不创建,就这么简单。
**/
/**
public SwaggerProperties swaggerProperties(){
return new SwaggerProperties();
} //使用的描述文件,这边就是一个类,可以当做属性文件
**/
@Bean
public Docket createApi() {
/**
ParameterBuilder contentType = new ParameterBuilder();
List
pars = new ArrayList<>();contentType.name(CONTENT_TYPE)
.defaultValue(MediaType.APPLICATION_JSON_UTF8_VALUE)
.allowableValues(new AllowableListValues(Lists.newArrayList(MediaType.MULTIPART_FORM_DATA_VALUE, MediaType.APPLICATION_JSON_UTF8_VALUE,MediaType.APPLICATION_OCTET_STREAM_VALUE), "string"))
.modelRef(new ModelRef("string"))
.parameterType(HEADER)
.required(false)
.build();
pars.add(contentType.build());
//noinspection Guava
return new Docket(DocumentationType.SWAGGER_2)
.groupName("buc-admin-finance")//分组名
.apiInfo(getApiInfo())//
.host(swaggerProperties().getHost())
.protocols(Sets.newHashSet("http", "https"))//使用协议
.produces(Sets.newHashSet(MediaType.ALL_VALUE, MediaType.APPLICATION_JSON_UTF8_VALUE))// For example, "application/json, application/xml"
.consumes(Sets.newHashSet(MediaType.ALL_VALUE, MediaType.APPLICATION_JSON_UTF8_VALUE, MediaType.MULTIPART_FORM_DATA_VALUE))// For example, "application/json, application/xml"
.select() //选择那些路径和api会生成document
.apis(Predicates.not(RequestHandlerSelectors.withClassAnnotation(SwaggerIgnore.class))) //对哪些api进行监控
.apis(Predicates.not(RequestHandlerSelectors.withMethodAnnotation(SwaggerIgnore.class)))
.apis(RequestHandlerSelectors.basePackage("com.best.buc.finance.controller"))
.paths(PathSelectors.any())//对所有路径进行监控
.build()
.securitySchemes(getSecuritySchemes())
.securityContexts(getSecurityContexts())
.globalOperationParameters(pars);
**/
//以下是最简单的实现,上面注释掉的是自己项目里的东西。
/**
Docket类的方法:
Docket groupName(String var):设置栏目名
Docket apiInfo(ApiInfo apiInfo):设置文档信息
Docket pathMapping(String path):设置api根路径
Docket protocols(Set
protocols):设置协议,Sets为com.goolge.common下的类,Sets.newHashSet("https","http")相当于new HashSet(){{add("https");add("http");}}; ApiSelectorBuilder select():初始化并返回一个API选择构造器
**/
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("cn.saytime.web"))//!此处为项目controller类所在的包目录
.paths(PathSelectors.any())
.build();
}
/**
createRestApi函数创建Docket的Bean之后,apiInfo()用来创建该Api的基本信息(这些基本信息会展现在文档页面中)。
**/
private ApiInfo getApiInfo(){
/**
return new ApiInfoBuilder()
.title(swaggerProperties().getTitle())
.description(swaggerProperties().getDescription())
.termsOfServiceUrl(swaggerProperties().getTermsOfServiceUrl())
.contact(new Contact(swaggerProperties().getContactName(), swaggerProperties().getContactUrl(), swaggerProperties().getContactEmail()))
.version(swaggerProperties().getVersion())
.license(swaggerProperties().getLicense())
.licenseUrl(swaggerProperties().getLicenseUrl())
.build();
**/
//以上是自己项目的代码(可以忽略),以下是最简单的获取API信息类的实现。
return new ApiInfoBuilder()
.title("springboot利用swagger构建api文档")
.description("写上对应的swagger文档的描述")
.termsOfServiceUrl("对应的分组")
.version("1.0")
.build();
}
private List
getSecuritySchemes() { return Lists.newArrayList(new ApiKey(AUTHORIZATION_HEADER, AUTHORIZATION_HEADER, HEADER));
}
private List
getSecurityContexts() { return Lists.newArrayList(
SecurityContext.builder().
securityReferences(defaultAuth())
.forPaths(PathSelectors.any())
.build());
}
private List
defaultAuth() { AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return Lists.newArrayList(SecurityReference.builder()
.reference(AUTHORIZATION_HEADER)
.scopes(authorizationScopes).build());
}
}
Controller
几个重要的注解说明:
- @Api()用于类;
表示标识这个类是swagger的资源
- @ApiOperation()用于方法;
表示一个http请求的操作 ,( value用于方法描述 notes用于提示内容 tags可以重新分组(视情况而用) )
- @ApiParam()用于方法,参数,字段说明;
表示对参数的添加元数据(说明或是否必填等) name–参数名 value–参数说明 required–是否必填,如 public User getUserInfo(@ApiParam(name="id",value="用户id",required=true) Long id,@ApiParam(name="username",value="用户名") String username)
- @ApiModel()用于类
表示对类进行说明,用于参数用实体类接收 , value–表示对象名 description–描述
- @ApiModelProperty()用于方法,字段
表示对model属性的说明或者数据操作更改 value–字段说明 name–重写属性名字 dataType–重写属性类型 required–是否必填 example–举例说明 hidden–隐藏
- @ApiIgnore()用于类,方法,方法参数
表示这个方法或者类被忽略
- @ApiImplicitParam() 用于方法
表示单独的请求参数
- @ApiImplicitParams() 用于方法,包含多个 @ApiImplicitParam
import cn.saytime.bean.JsonResult;
import cn.saytime.bean.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author zh
* @ClassName cn.saytime.web.UserController
* @Description
*/
@RestController
public class UserController{
// 创建线程安全的Map
static Map
users = Collections.synchronizedMap( new HashMap()); /**
* 根据ID查询用户
* @param id
* @return
*/
@ApiOperation(value="获取用户详细信息", notes="根据url的id来获取用户详细信息")
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Integer", paramType = "path")
@RequestMapping(value = "user/{id}", method = RequestMethod.GET)
public ResponseEntity
getUserById ( @PathVariable(value = "id") Integer id){JsonResult r = new JsonResult();
try {
User user = users.get(id);
r.setResult(user);
r.setStatus("ok");
} catch (Exception e) {
r.setResult(e.getClass().getName() + ":" + e.getMessage());
r.setStatus("error");
e.printStackTrace();
}
return ResponseEntity.ok(r);
}
/**
* 查询用户列表
* @return
*/
@ApiOperation(value="获取用户列表", notes="获取用户列表")
@RequestMapping(value = "users", method = RequestMethod.GET)
public ResponseEntity
getUserList (){ JsonResult r = new JsonResult();
try {
List
userList = new ArrayList(users.values()); r.setResult(userList);
r.setStatus("ok");
} catch (Exception e) {
r.setResult(e.getClass().getName() + ":" + e.getMessage());
r.setStatus("error");
e.printStackTrace();
}
return ResponseEntity.ok(r);
}
/**
* 添加用户
* @param user
* @return
*/
@ApiOperation(value="创建用户", notes="根据User对象创建用户")
@ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
@RequestMapping(value = "user", method = RequestMethod.POST)
public ResponseEntity
add ( @RequestBody User user){JsonResult r = new JsonResult();
try {
users.put(user.getId(), user);
r.setResult(user.getId());
r.setStatus("ok");
} catch (Exception e) {
r.setResult(e.getClass().getName() + ":" + e.getMessage());
r.setStatus("error");
e.printStackTrace();
}
return ResponseEntity.ok(r);
}
/**
* 根据id删除用户
* @param id
* @return
*/
@ApiOperation(value="删除用户", notes="根据url的id来指定删除用户")
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long", paramType = "path")
@RequestMapping(value = "user/{id}", method = RequestMethod.DELETE)
public ResponseEntity
delete ( @PathVariable(value = "id") Integer id){JsonResult r = new JsonResult();
try {
users.remove(id);
r.setResult(id);
r.setStatus("ok");
} catch (Exception e) {
r.setResult(e.getClass().getName() + ":" + e.getMessage());
r.setStatus("error");
e.printStackTrace();
}
return ResponseEntity.ok(r);
}
/**
* 根据id修改用户信息
* @param user
* @return
*/
@ApiOperation(value="更新信息", notes="根据url的id来指定更新用户信息")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long",paramType = "path"),
@ApiImplicitParam(name = "user", value = "用户实体user", required = true, dataType = "User")
})
@RequestMapping(value = "user/{id}", method = RequestMethod.PUT)
public ResponseEntity
update ( @PathVariable("id") Integer id, @RequestBody User user){JsonResult r = new JsonResult();
try {
User u = users.get(id);
u.setUsername(user.getUsername());
u.setAge(user.getAge());
users.put(id, u);
r.setResult(u);
r.setStatus("ok");
} catch (Exception e) {
r.setResult(e.getClass().getName() + ":" + e.getMessage());
r.setStatus("error");
e.printStackTrace();
}
return ResponseEntity.ok(r);
}
@ApiIgnore//使用该注解忽略这个API
@RequestMapping(value = "/hi", method = RequestMethod.GET)
public String jsonTest() {
return " hi you!";
}
}
Json格式输出类 JsonResult.class
public class JsonResult {
private String status = null;
private Object result = null;
// Getter Setter
}
实体类
import java.util.Date;
/**
* @author zh
* @ClassName cn.saytime.bean.User
* @Description
*/
public class User {
private int id;
private String username;
private int age;
private Date ctm;
// Getter Setter
}
最后打开localhost:8080/swagger-ui.html