您好,登錄后才能下訂單哦!
在開發服務端的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里面
@ApiOperation
@ApiResponses
@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
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。