springboot集成swagger-UI開發(fā)API項目

   在開發(fā)服務(wù)端的API工程的時候,我們可以把swagger插件集成到我們的項目里面來,這樣可以后臺開發(fā)人員直接用可視化界面進行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;

梧州網(wǎng)站制作公司哪家好,找創(chuàng)新互聯(lián)!從網(wǎng)頁設(shè)計、網(wǎng)站建設(shè)、微信開發(fā)、APP開發(fā)、自適應(yīng)網(wǎng)站建設(shè)等網(wǎng)站項目制作,到程序開發(fā),運營維護。創(chuàng)新互聯(lián)2013年開創(chuàng)至今到現(xiàn)在10年的時間,我們擁有了豐富的建站經(jīng)驗和運維經(jīng)驗,來保證我們的工作的順利進行。專注于網(wǎng)站建設(shè)就選創(chuàng)新互聯(lián)。

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主要就是定義掃描的路徑從中找出標(biāo)識了需要裝配的類自動裝配到spring的bean容器中 表明com.vicrab.api包里面的對象需要被裝載到Spring的bean容器

@MapperScan :MapperScan標(biāo)注的包能夠讓別的類對被標(biāo)注的類進行引用

部分實例代碼:

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 = "根據(jù)郵箱獲取用戶信息", 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 用在參數(shù)對象的字段上

協(xié)議集描述 @Api 用在Conntroller類上

協(xié)議描述 @ApiOperation 用在controller方法上

Response集 @ApiResponses 用在controller方法上

Response @ApiResponse 用在@ApiResponses里面


@api : value - 字段說明 ,description - 注釋說明這個類

@ApiOperation

value - 字段說明
notes - 注釋說明
httpMethod - 說明這個方法被請求的方式
response - 方法的返回值的類型

@ApiResponses

code - 響應(yīng)的HTTP狀態(tài)碼
message - 響應(yīng)的信息內(nèi)容
response - 方法的返回值的類型

@ApiParam @PathVariable @RequestParam三者區(qū)別

A .@ApiParam 顧名思義,是注解api的參數(shù),也就是用于swagger提供開發(fā)者文檔,文檔中生成的注釋內(nèi)容。

@ApiOperation( value = "編輯公告", notes = "編輯公告", httpMethod = "POST" )
@RequestMapping( value = "/edit", method = RequestMethod.POST )
public RequestResult edit(
@ApiParam(name = "title", value = "公告標(biāo)題", required = true) @RequestParam("title") String title,
@ApiParam(name = "content", value = "公告內(nèi)容", required = true) @RequestParam("content") String content){
B .@RequestParam,是獲取前端傳遞給后端的參數(shù),可以是get方式,也可以是post方式。其中如果前端傳遞的參數(shù)和后端你接受的參數(shù)起的名字字段是一致的可以省略不寫,也可以直接寫@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 = "公告標(biāo)題", required = true) @RequestParam String title,
@ApiParam(name = "content", value = "公告內(nèi)容", required = true) String content,
C .@PathVariable,是獲取get方式,url后面參數(shù),進行參數(shù)綁定

@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) {

    部分實現(xiàn)代碼:

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

網(wǎng)頁標(biāo)題:springboot集成swagger-UI開發(fā)API項目
網(wǎng)頁路徑:http://www.muchs.cn/article14/phohde.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站設(shè)計公司、、搜索引擎優(yōu)化自適應(yīng)網(wǎng)站、軟件開發(fā)、網(wǎng)站建設(shè)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

外貿(mào)網(wǎng)站建設(shè)