smart-doc使用注释生成文档

使用注释生成文档

官网:https://github.com/smart-doc-group/smart-doc

文档地址:https://smart-doc-group.github.io/#/start/javadoc

1.最新依赖

<plugin>
    <groupId>com.github.shalousun</groupId>
    <artifactId>smart-doc-maven-plugin</artifactId>
    <version>2.6.2</version>
    <!--配置文件位置-->
    <configuration>
        <configFile>./src/main/resources/doc/smart-doc.json</configFile>
        <projectName>商铺接口文档</projectName>
        <!--项目编译时执行生成html 不需要可以去掉executions 标签 -->
        <includes>
            <include>com.hmdp.*</include>
        </includes>
    </configuration>
    <executions>
        <execution>
            <phase>compile</phase>
            <goals>
                <goal>html</goal>
            </goals>
        </execution>
    </executions>
</plugin>
  1. 创建文档配置文件
{
  "outPath": "D:/doc",
  "createDebugPage": true,
  "allInOne": true,//是否将文档合并为一个文件,一般建议为真。
  "coverOld": true,
  "projectName": "商铺接口文档",
  "packageFilters": "com.hmdp.controller.ShopController" //配置多个用逗号隔开
}
  1. controller注解实例
/**
 * 商铺控制器
 * @author 虎哥
 * @since 2021-12-22
 */
@RestController
@RequestMapping("/shop")
public class ShopController {

    @Resource
    public IShopService shopService;

    /**
     * 根据id查询商铺信息
     * @param id 商铺id
     * @return 商铺详情数据
     */
    @GetMapping("/{id}")
    public Result<Shop> queryShopById(@PathVariable("id") Long id) {
        return shopService.queryById(id);
    }

    /**
     * 新增商铺信息
     * @param shop 商铺数据
     * @return 商铺id
     */
    @PostMapping
    public Result<Long> saveShop(@RequestBody Shop shop) {
        // 写入数据库
        shopService.save(shop);
        // 返回店铺id
        return Result.ok(shop.getId());
    }

    /**
     * 更新商铺信息
     * @param shop 商铺数据
     * @return 无
     */
    @PutMapping
    public Result<Object> updateShop(@RequestBody Shop shop) {
        // 写入数据库
        shopService.updateById(shop);
        return Result.ok();
    }

    /**
     * 根据商铺类型分页查询商铺信息
     * @param typeId 商铺类型
     * @param current 页码
     * @return 商铺列表
     */
    @GetMapping("/of/type")
    public Result<List<Shop>> queryShopByType(
            @RequestParam("typeId") Integer typeId,
            @RequestParam(value = "current", defaultValue = "1") Integer current
    ) {
        // 根据类型分页查询
        Page<Shop> page = shopService.query()
                .eq("type_id", typeId)
                .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
        // 返回数据
        return Result.ok(page.getRecords());
    }

    /**
     * 根据商铺名称关键字分页查询商铺信息
     * @param name 商铺名称关键字
     * @param current 页码
     * @return 商铺列表
     */
    @GetMapping("/of/name")
    public Result<List<Shop>> queryShopByName(
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "current", defaultValue = "1") Integer current
    ) {
        // 根据类型分页查询
        Page<Shop> page = shopService.query()
                .like(StrUtil.isNotBlank(name), "name", name)
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 返回数据
        return Result.ok(page.getRecords());
    }
}

  1. 数据对象加注解
/**
 * 商铺对象
 * @author 虎哥
 * @since 2021-12-22
 */
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("tb_shop")
public class Shop implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 主键
     */
    @TableId(value = "id", type = IdType.AUTO)
    private Long id;

    /**
     * 商铺名称
     */
    private String name;

    /**
     * 商铺类型的id
     */
    private Long typeId;

    /**
     * 商铺图片,多个图片以','隔开
     */
    private String images;

    /**
     * 商圈,例如陆家嘴
     */
    private String area;

    /**
     * 地址
     */
    private String address;

    /**
     * 经度
     */
    private Double x;

    /**
     * 维度
     */
    private Double y;

    /**
     * 均价,取整数
     */
    private Long avgPrice;

    /**
     * 销量
     */
    private Integer sold;

    /**
     * 评论数量
     */
    private Integer comments;

    /**
     * 评分,1~5分,乘10保存,避免小数
     */
    private Integer score;

    /**
     * 营业时间,例如 10:00-22:00
     */
    private String openHours;

    /**
     * 创建时间
     */
    private LocalDateTime createTime;

    /**
     * 更新时间
     */
    private LocalDateTime updateTime;


    @TableField(exist = false)
    private Double distance;
}
  1. 在maven插件生成接口文档

Controller使用的其他注解

@param	对于 Spring 引导接口层,对于简单的类型参数,在使用 @param 时必须编写注释描述,对于实体类型 smart-doc,则不会被选中。
@deprecated	可以在注释中用于标记接口已过时,效果与@Deprecated注释相同
@apiNote	@apiNoteJava的新文档标签,smart-doc使用@apiNote作为该方法的详细说明,因此您可以使用apiNote编写长笔记。如果方法不写@apiNote标注说明,smart-doc 直接使用方法默认标注填写
  • 设置基本类型请求参数的模拟值Bob
/**
 * Test @RequestParam
 *
 * @param author author|Bob
 * @param type   type
 */
@GetMapping("testRequestParam")
public void testRequestParam(@RequestParam String author, @RequestParam String type) {

}

作者的模拟值在 |上面的符号Bob

  • 参数对象替换
/**
 * 接口描述
 * @param pageable com.power.doc.model.PageRequestDto
 * @return
 */
@PostMapping(value = "/enum/resp")
public SimpleEnum resp(@RequestBody Pageable pageable){
    return null;
}
  • 输入参数还支持泛型
@param pageable com.power.doc.model.PageRequestDto
@param pageable Your comment|com.power.doc.model.PageRequestDto
# smart-doc itself is based on generic derivation, if you need generics, you need to write specific objects
@param pageable com.power.doc.model.PageRequestDto<com.power.doc.model.User>

自定义文档标签

@ignore使用

该参数不参与文档生成

public class SubUser {

    /**
     * user name
     */
    private String subUserName;

    /**
     * ID card
     */
    private String idCard;

    /**
     * gender
     */
    private int gender;

    /**
     *  createTime
     *  @ignore
     */
    private Timestamp createTime;

}

@required使用

加了代表参数是必填项

public class SubUser {

    /**
     * user name
     */
    private String subUserName;

    /**
     * ID card
     */
    private String idCard;

    /**
     * gender
     * @required
     */
    private int gender;

    /**
     *  createTime
     *  @ignore
     */
    private Timestamp createTime;

}

@mock使用

会为这个必填项生成一个实例参数

public class SimpleUser {

    /**
     * user name
     * @mock Bob
     * @since v1.0
     */
    @NotNull
    private String username;

    /**
     * password
     * @mock 12356
     * @since v1.0
     */
    private String password;

}

@download使用

用来告诉智能文档。控制器中的方法之一是文件下载界面。当 smart-doc 生成调试页面时,它可以生成文件下载请求。后台参考代码如下:

/**
 * File download test
 *
 * @author yu 2020/12/14.
 */
@RestController
@RequestMapping("download")
public class DownloadController extends BaseController {
    private static final Logger LOGGER = LoggerFactory.getLogger(DownloadController.class);
    /**
     * Download normal files
     *
     * @param response
     * @return
     * @throws IOException
     * @download
     */
    @PostMapping("text/{id}")
    public void download(HttpServletResponse response) throws IOException {
        String randomStr = RandomUtil.randomNumbers(50);
        String fileName = "test.log";
        //To use the smart-doc debug page to test the file download, you must set the filename response header, otherwise, use other simulation tools to test.
        // urlDecode is used to process the file name
        response.setHeader("filename", urlEncode(fileName));// No need to set this since 2.0.2
        ServletOutputStream outputStream = this.downloadText(fileName, response);
        outputStream.write(randomStr.getBytes());
    }

    public String urlEncode(String str) {
        if (StringUtil.isEmpty(str)) {
            return null;
        } else {
            try {
                return java.net.URLEncoder.encode(str, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return null;
            }
        }
    }
}

通用数据返回类

设计结果数据对象

  1. 设计类似的通用返回数据结构
public abstract class BaseResult<T> implements Serializable {

    private boolean success = false;

    private String message;

    private T data;

    private String code;

    private String timestamp;
}
  1. 编写静态返回工具类
public class CommonResult<T> extends BaseResult implements Serializable {

    private static final long serialVersionUID = -7268040542410707954L;

    public CommonResult() {

    }

    public CommonResult(boolean success, String message) {
        this.setSuccess(success);
        this.setMessage(message);
    }

    public CommonResult(boolean success) {
        this.setSuccess(success);
    }

    public CommonResult(String code, String message) {
        this.setCode(code);
        this.setMessage(message);
    }

    public CommonResult(boolean success, String message, T data) {
        this.setSuccess(success);
        this.setMessage(message);
        this.setData(data);
    }

    public static CommonResult ok() {
        return ok(BaseErrorCode.Common.SUCCESS);
    }

    public static <T> CommonResult<T> ok(IMessage msg) {
        return baseCreate(msg.getCode(), msg.getMessage(), true);
    }

    public static CommonResult fail() {
        return fail(BaseErrorCode.Common.UNKNOWN_ERROR);
    }

    public static CommonResult fail(IMessage message) {
        return fail(message.getCode(), message.getMessage());
    }

    public static CommonResult fail(String code, String msg) {
        return baseCreate(code, msg, false);
    }

    private static <T> CommonResult<T> baseCreate(String code, String msg, boolean success) {
        CommonResult result = new CommonResult();
        result.setCode(code);
        result.setSuccess(success);
        result.setMessage(msg);
        result.setTimestamp(DateTimeUtil.nowStrTime());
        return result;
    }

    public CommonResult<T> setResult(T data) {
        this.setData(data);
        return this;
    }

    public T getData() {
        return (T) super.getData();
    }
}

接口示例

/**
 * Add user information
 * @param user
 * @return
 */
@PostMapping("/add")
public CommonResult<User> addUser(@RequestBody User user){
    return CommonResult.ok().setResult(user);
}

泛型命名约定

使用 smart-doc 时,我们建议在代码中使用以下规范来定义 JAVA 泛型, 不规则的定义可能会导致 smart-doc 无法正确解析源代码

虽然没有强制性的命名约定,但为了方便代码阅读,形成了一些常规的命名约定,如下:

  • T:类型(Java类)一般泛型类型,通常作为第一个泛型类型
  • S:通用泛型类型,如果需要使用多个泛型类型,可以使用S作为第二泛型类型
  • U:通用泛型类型,如果需要使用多个泛型类型,可以使用U作为第三泛型类型
  • V:通用泛型类型,如果需要使用多个泛型类型,可以使用V作为第四个泛型类型
  • E:集合元素泛型类型,主要用于定义集合泛型类型
  • K:映射键泛型类型,主要用于定义映射泛型类型
  • V:映射值泛型类型,主要用于定义映射泛型类型
  • N:数字数字泛型类型,主要用于定义数值类型的泛型类型
  • ?:表示不确定的 Java 类型
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值