真实的国产乱ⅩXXX66竹夫人,五月香六月婷婷激情综合,亚洲日本VA一区二区三区,亚洲精品一区二区三区麻豆

成都創(chuàng)新互聯(lián)網(wǎng)站制作重慶分公司

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

   在開發(fā)服務(wù)端的API工程的時(shí)候,我們可以把swagger插件集成到我們的項(xiàng)目里面來,這樣可以后臺(tái)開發(fā)人員直接用可視化界面進(jìn)行test 比較方便快捷。一段測(cè)試代碼案例:

         pom.xml
           
        io.springfox
        springfox-swagger2
        ${version.springfox}
    

    
        io.springfox
        springfox-swagger-ui
        ${version.springfox}
    

    
        com.github.xiaoymin
        swagger-bootstrap-ui
        ${version.swagger-bootstrap-ui}
    

    
        io.swagger
        swagger-annotations
        ${version.swagger}
    

    
        io.swagger
        swagger-models
        ${version.swagger}
    

package com.vicrab.api.server;

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

@EnableSwagger2 :?jiǎn)⒂胹wagger項(xiàng)目

@ComponentScan(basePackages = {"com.vicrab.api"}) :@ComponentScan主要就是定義掃描的路徑從中找出標(biāo)識(shí)了需要裝配的類自動(dòng)裝配到spring的bean容器中 表明com.vicrab.api包里面的對(duì)象需要被裝載到Spring的bean容器

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

部分實(shí)例代碼:

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 getUser(@ApiParam(value = "用戶key", required = true) @PathVariable("user_key") String userKey) {
    // do some magic!
    return new ResponseEntity(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 getUserByEmail(@NotNull @ApiParam(value = "用戶郵箱", required = true) @RequestParam(value = "user_email", required = true) String userEmail) {
    // do some magic!
    return new ResponseEntity(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 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(HttpStatus.OK);
}

作用范圍 API 使用位置

對(duì)象屬性 @ApiModelProperty 用在參數(shù)對(duì)象的字段上

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

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

Response集 @ApiResponses 用在controller方法上

Response @ApiResponse 用在@ApiResponses里面


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

@ApiOperation

value - 字段說明
notes - 注釋說明
httpMethod - 說明這個(gè)方法被請(qǐng)求的方式
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ù),進(jìn)行參數(shù)綁定

@ApiOperation(value = "刪除公告", notes = "刪除公告", httpMethod = "POST")
@RequestMapping(value = "/delete/{bisKey}", method = RequestMethod.POST)
public RequestResult remove(@ApiParam(name = "bisKey", value = "需要?jiǎng)h除的公告ids", required = true) @PathVariable String bisKey) {

    部分實(shí)現(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 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, HttpStatus.BAD_REQUEST);
        }
        User user = userService.getUser(userKey);
        operateResult = OperateResult.success(user);
        return new ResponseEntity(operateResult, HttpStatus.OK);
    } catch (Exception e) {
        logger.error("api getUser error.{}", e);
        operateResult = OperateResult.exception(OperateCode.SYSTEM_ERROR, e);
        return new ResponseEntity(operateResult, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

@Override
public ResponseEntity 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, HttpStatus.BAD_REQUEST);
        }
        operateResult = userService.getUserByEmail(userEmail);

        return new ResponseEntity(operateResult, HttpStatus.OK);
    } catch (Exception e) {
        logger.error("api getUser error.{}", e);
        operateResult = OperateResult.exception(OperateCode.SYSTEM_ERROR, e);
        return new ResponseEntity(operateResult, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

@Override
public ResponseEntity 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, HttpStatus.BAD_REQUEST);
        }
        // 驗(yàn)證郵箱
        if (!MailUtils.verifyEmail(userEmail)) {
            operateResult = OperateResult.set(OperateCode.EMAIL_PATTERN_ERROR);
            return new ResponseEntity(operateResult, HttpStatus.BAD_REQUEST);
        }

        VicrabResult vicrabResult = userService.login(userEmail, userPwd);
        operateResult = OperateResult.set(vicrabResult.getOperateCode(), vicrabResult.getData());
        return new ResponseEntity(operateResult, HttpStatus.OK);
    } catch (Exception e) {
        logger.error("api login error.{}", e);
        operateResult = OperateResult.exception(OperateCode.SYSTEM_ERROR, e);
        return new ResponseEntity(operateResult, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

這里重點(diǎn)介紹了很多的注解的意義 。下載swagger-ui項(xiàng)目,
把包含doc.html的目錄一層放到src/main/resources目錄下面,啟動(dòng)訪問 http://ip:port/doc.html

網(wǎng)頁(yè)名稱:springboot集成swagger-UI開發(fā)API項(xiàng)目
網(wǎng)站URL:http://weahome.cn/article/phohde.html

其他資訊

在線咨詢

微信咨詢

電話咨詢

028-86922220(工作日)

18980820575(7×24)

提交需求

返回頂部