在开发服务端的API工程的时候,我们可以把swagger插件集成到我们的项目里面来,这样可以后台开发人员直接用可视化界面进行test 比较方便快捷。一段测试代码案例:
pom.xml
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${version.springfox}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${version.springfox}</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>${version.swagger-bootstrap-ui}</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>${version.swagger}</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
<version>${version.swagger}</version>
</dependency>
package com.vicrab.api.server;
import com.vicrab.api.datasource.MongoDBTemplateRegister;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.ExitCodeGenerator;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication
@EnableSwagger2
@ComponentScan(basePackages = {"com.vicrab.api"})
@MapperScan("com.vicrab.api.repository.mapper")
@Import(MongoDBTemplateRegister.class)
public class Swagger2SpringBoot implements CommandLineRunner {
@Override
public void run(String... arg0) throws Exception {
if (arg0.length > 0 && arg0[0].equals("exitcode")) {
throw new ExitException();
}
}
public static void main(String[] args) throws Exception {
new SpringApplication(Swagger2SpringBoot.class).run(args);
}
class ExitException extends RuntimeException implements ExitCodeGenerator {
private static final long serialVersionUID = 1L;
@Override
public int getExitCode() {
return 10;
}
}
}
注解解释:
@SpringBootApplication :Springboot项目专用注解
@EnableSwagger2 :启用swagger项目
@ComponentScan(basePackages = {"com.vicrab.api"}) :@ComponentScan主要就是定义扫描的路径从中找出标识了需要装配的类自动装配到spring的bean容器中 表明com.vicrab.api包里面的对象需要被装载到Spring的bean容器
@MapperScan :MapperScan标注的包能够让别的类对被标注的类进行引用
部分实例代码:
package com.vicrab.api.server.api;
import com.vicrab.api.server.model.OperateResult;
import com.vicrab.api.server.model.UserBase;
import com.vicrab.api.server.model.UserRegister;
import io.swagger.annotations.*;
import org.springframework.http.HttpStatus;
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.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
import javax.validation.constraints.*;
import javax.validation.Valid;
@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2019-04-19T17:09:30.945+08:00")
@Api(value = "user", tags = {"user",}, description = "the user API")
public interface UserApi {
@ApiOperation(value = "获取用户信息", notes = "get_user", response = OperateResult.class, tags = {"user",})
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK", response = OperateResult.class),
@ApiResponse(code = 500, message = "system error", response = Void.class)})
@RequestMapping(value = "/user/{user_key}",
produces = {"application/json"},
method = RequestMethod.GET)
default ResponseEntity<OperateResult> getUser(@ApiParam(value = "用户key", required = true) @PathVariable("user_key") String userKey) {
// do some magic!
return new ResponseEntity<OperateResult>(HttpStatus.OK);
}
@ApiOperation(value = "根据邮箱获取用户信息", notes = "get_user_by_email", response = OperateResult.class, tags = {"user",})
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK", response = OperateResult.class),
@ApiResponse(code = 500, message = "system error", response = Void.class)})
@RequestMapping(value = "/user/email",
produces = {"application/json"},
method = RequestMethod.GET)
default ResponseEntity<OperateResult> getUserByEmail(@NotNull @ApiParam(value = "用户邮箱", required = true) @RequestParam(value = "user_email", required = true) String userEmail) {
// do some magic!
return new ResponseEntity<OperateResult>(HttpStatus.OK);
}
@ApiOperation(value = "用户登录", notes = "login", response = OperateResult.class, tags = {"user",})
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK", response = OperateResult.class),
@ApiResponse(code = 500, message = "system error", response = Void.class)})
@RequestMapping(value = "/user/login",
produces = {"application/json"},
method = RequestMethod.POST)
default ResponseEntity<OperateResult> login(@NotNull @ApiParam(value = "用户邮箱", required = true) @RequestParam(value = "user_email", required = true) String userEmail, @NotNull @ApiParam(value = "用户密码", required = true) @RequestParam(value = "user_pwd", required = true) String userPwd) {
// do some magic!
return new ResponseEntity<OperateResult>(HttpStatus.OK);
}
作用范围 API 使用位置
对象属性 @ApiModelProperty 用在参数对象的字段上
协议集描述 @Api 用在Conntroller类上
协议描述 @ApiOperation 用在controller方法上
Response集 @ApiResponses 用在controller方法上
Response @ApiResponse 用在@ApiResponses里面
@api : value – 字段说明 ,description – 注释说明这个类
@ApiOperation
value – 字段说明
notes – 注释说明
httpMethod – 说明这个方法被请求的方式
response – 方法的返回值的类型
@ApiResponses
code – 响应的HTTP状态码
message – 响应的信息内容
response – 方法的返回值的类型
@ApiParam @PathVariable @RequestParam三者区别
A .@ApiParam 顾名思义,是注解api的参数,也就是用于swagger提供开发者文档,文档中生成的注释内容。
@ApiOperation( value = "编辑公告", notes = "编辑公告", httpMethod = "POST" )
@RequestMapping( value = "/edit", method = RequestMethod.POST )
public RequestResult edit(
@ApiParam(name = "title", value = "公告标题", required = true) @RequestParam("title") String title,
@ApiParam(name = "content", value = "公告内容", required = true) @RequestParam("content") String content){
B .@RequestParam,是获取前端传递给后端的参数,可以是get方式,也可以是post方式。其中如果前端传递的参数和后端你接受的参数起的名字字段是一致的可以省略不写,也可以直接写@RequestParam String title,如果不一致一定要完整写,不然获取不到,如下面的bis_key就必须写。
@ApiOperation( value = "编辑公告", notes = "编辑公告", httpMethod = "POST" )
@RequestMapping( value = "/edit", method = RequestMethod.POST )
public RequestResult edit(
@ApiParam(name = "bis_key", value = "bis_key", required = true) String bisKey,
@ApiParam(name = "title", value = "公告标题", required = true) @RequestParam String title,
@ApiParam(name = "content", value = "公告内容", required = true) String content,
C .@PathVariable,是获取get方式,url后面参数,进行参数绑定
@ApiOperation(value = "删除公告", notes = "删除公告", httpMethod = "POST")
@RequestMapping(value = "/delete/{bisKey}", method = RequestMethod.POST)
public RequestResult remove(@ApiParam(name = "bisKey", value = "需要删除的公告ids", required = true) @PathVariable String bisKey) {
部分实现代码:
import com.vicrab.api.bean.VicrabResult;
import com.vicrab.api.log.AuditLogAnnotation;
import com.vicrab.api.log.AuditLogEnum;
import com.vicrab.api.server.model.User;
import com.vicrab.api.server.model.UserBase;
import com.vicrab.api.server.model.UserRegister;
import com.vicrab.api.server.api.UserApi;
import com.vicrab.api.bean.OperateCode;
import com.vicrab.api.server.model.OperateResult;
import com.vicrab.api.service.UserService;
import com.vicrab.api.utils.MailUtils;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import javax.validation.constraints.*;
import javax.validation.Valid;
@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2018-03-16T11:20:10.134+08:00")
@Controller
public class UserApiController implements UserApi {
private static final Logger logger = LoggerFactory.getLogger(UserApiController.class);
@Autowired
private UserService userService;
@Override
public ResponseEntity<OperateResult> getUser(@ApiParam(value = "用户key", required = true) @PathVariable("user_key") String userKey) {
OperateResult operateResult = new OperateResult();
try {
if (StringUtils.isBlank(userKey)) {
operateResult = OperateResult.set(OperateCode.PARAM_ERROR);
return new ResponseEntity<OperateResult>(operateResult, HttpStatus.BAD_REQUEST);
}
User user = userService.getUser(userKey);
operateResult = OperateResult.success(user);
return new ResponseEntity<OperateResult>(operateResult, HttpStatus.OK);
} catch (Exception e) {
logger.error("api getUser error.{}", e);
operateResult = OperateResult.exception(OperateCode.SYSTEM_ERROR, e);
return new ResponseEntity<OperateResult>(operateResult, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@Override
public ResponseEntity<OperateResult> getUserByEmail(@NotNull @ApiParam(value = "用户邮箱", required = true) @RequestParam(value = "user_email", required = true) String userEmail) {
OperateResult operateResult = new OperateResult();
try {
if (StringUtils.isBlank(userEmail)) {
operateResult = OperateResult.set(OperateCode.PARAM_ERROR);
return new ResponseEntity<OperateResult>(operateResult, HttpStatus.BAD_REQUEST);
}
operateResult = userService.getUserByEmail(userEmail);
return new ResponseEntity<OperateResult>(operateResult, HttpStatus.OK);
} catch (Exception e) {
logger.error("api getUser error.{}", e);
operateResult = OperateResult.exception(OperateCode.SYSTEM_ERROR, e);
return new ResponseEntity<OperateResult>(operateResult, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@Override
public ResponseEntity<OperateResult> login(@NotNull @ApiParam(value = "用户邮箱", required = true) @RequestParam(value = "user_email", required = true) String userEmail, @NotNull @ApiParam(value = "用户密码", required = true) @RequestParam(value = "user_pwd", required = true) String userPwd) {
OperateResult operateResult = new OperateResult();
try {
if (StringUtils.isBlank(userEmail) || StringUtils.isBlank(userPwd)) {
operateResult = OperateResult.set(OperateCode.PARAM_ERROR);
return new ResponseEntity<OperateResult>(operateResult, HttpStatus.BAD_REQUEST);
}
// 验证邮箱
if (!MailUtils.verifyEmail(userEmail)) {
operateResult = OperateResult.set(OperateCode.EMAIL_PATTERN_ERROR);
return new ResponseEntity<OperateResult>(operateResult, HttpStatus.BAD_REQUEST);
}
VicrabResult<User> vicrabResult = userService.login(userEmail, userPwd);
operateResult = OperateResult.set(vicrabResult.getOperateCode(), vicrabResult.getData());
return new ResponseEntity<OperateResult>(operateResult, HttpStatus.OK);
} catch (Exception e) {
logger.error("api login error.{}", e);
operateResult = OperateResult.exception(OperateCode.SYSTEM_ERROR, e);
return new ResponseEntity<OperateResult>(operateResult, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
这里重点介绍了很多的注解的意义 。下载swagger-ui项目,
把包含doc.html的目录一层放到src/main/resources目录下面,启动访问 http://ip:port/doc.html
原创文章,作者:3628473679,如若转载,请注明出处:https://blog.ytso.com/197818.html