本文最后更新于 2024年11月24日 晚上
1. pom.xml
1 2 3 4 5 6 7 8 9 10 11 12
| <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-yaml</artifactId> <version>2.13.3</version> </dependency>
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.13.3</version> </dependency>
|
2. 文件结构
1 2 3 4 5 6 7 8 9
| . ├── Main.java └── pojo ├── Config.java ├── Qq.java ├── Feishu.java └── Dingtalk.java
config.yml
|
3. config.yml
yaml 中的层级关系,转化到 Java 中,类似于类的包裹
1 2 3 4 5 6 7 8 9 10 11
| qq: account: key:
feishu: account: key:
dingtalk: account: key:
|
4. Main.java
1 2 3 4 5
| public static void main(String[] args) throws Exception{ File f = new File("path_to_config.yml"); ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory()); Config config = objectMapper.readValue(f, Config.class); }
|
5. Config.java
1 2 3 4 5 6 7 8 9 10 11 12
| import lombok.Getter; import lombok.Setter;
@Setter @Getter public class Config { private Qq qq; private Feishu feishu; private DingTalk dingtalk; }
|
6. Qq/Feishu/Dingtalk.java
以 Qq.java 为例
1 2 3 4 5 6 7 8 9 10 11
| import lombok.Getter; import lombok.Setter;
import java.util.Arrays;
@Setter @Getter public class Qq { private Long account; private String key; }
|
7. 注意点
- yaml 中
@
等字符,可以使用单双引号包裹
- yaml 区分大小写
8. 参考
- YAML file read/parse and write in java| Latest tutorials: https://www.w3schools.io/file/yaml-java-read-write/