在使用编写代码的过程中,经常会写一些固定代码段。
以 Java 为例,定义实体类时一般都会编写序列化版本号:
@Serial
private static final long serialVersionUID = 1L;
这段代码是固定写法,基本不会变,如果每次都手写的话,就比较繁琐了。
VSCode 提供了生成代码段的功能,为我们提供了便利。步骤如下:
-
选择代码生成配置
-
选择文件后缀
上方出现了各种后缀文件的选择,这里以选择
java.json
为例:此时的
java.json
是没有实际内容的,只是以注释的方式提供了一个示例。 -
编写代码生成配置
这里以自用的两个代码生成为例:
java.json
:{"实现序列化接口": {"prefix": "is","body": ["implements Serializable "]},"序列号版本号": {"prefix": "ser","body": ["@Serial","private static final long serialVersionUID = 1L;"]},"单元测试方法": {"prefix": "test","body": ["@Test","public void test() {",""," $1","}"]},"Swagger控制层注解": {"prefix": "tag","body": ["@Tag(name = \"$1\")"]},"Swagger接口注解": {"prefix": "ope","body": ["@Operation(summary = \"$1\")"]},"Swagger类注解": {"prefix": "sch","body": ["@Schema(description = \"$1\")"]},"生成ArrayList": {"prefix": "list","body": ["List<$1> list = new ArrayList<>();"]},"生成HashSet": {"prefix": "set","body": ["Set<$1> set = new HashSet<>();"]},"生成HashMap": {"prefix": "map","body": ["Map<String, Object> $1 = new HashMap<>();"]},"时间": {"prefix": "pd","body": ["private Date "]},"整数": {"prefix": "pi","body": ["private Integer "]},"长整数": {"prefix": "pl","body": ["private Long "]},"当地时间": {"prefix": "pld","body": ["private LocalDateTime "]},"字符串": {"prefix": "ps","body": ["private String "]},"静态不变长整数": {"prefix": "psfl","body": ["public static final long "]},"静态不变字符串": {"prefix": "psfs","body": ["public static final String "]} }
xml.json
:{"MyBatis模板": {"prefix": "mybatis","body": ["<?xml version=\"1.0\" encoding=\"UTF-8\"?>","<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">","<mapper namespace=\"$1\">"," ","</mapper>"]} }
这样,以后在编写代码时,只需要使用配置的关键词就可以生成代码,比如一开始说的的序列化版本号代码输入 ser
即可生成。
环境:
- VS Code 1.93.1