参考
加载配置文件信息使用场景
- 游戏物品等策划配置的表格数据,如游戏物品名称,物品描述,物品图标等不会经常变动的数据,可以放在配置文件里,通过配置文件加载到内存中,减少数据库查询次数,提高性能。
配置文件加载方式
- 将表格获取其他数据的配置文件放在resources目录下。
- 定义数据结构相关的类
- 读取配置文件并使用
代码示例
- 将文件放在resources目录下,如src/main/resources/Prop.json1 
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17[ 
 {
 "tId": 1,
 "name": "珍珠",
 "desc": "购买/解锁。获取说明:通过土地每日固定产出,以及小游戏消耗/获取"
 },
 {
 "tId": 2,
 "name": "铲铲",
 "desc": "解锁沙滩专用。获取说明:官方派发"
 },
 {
 "tId": 3,
 "name": "奇异种子",
 "desc": "用于种植奇异果实。获取说明:通过加工农产品获得奇异种子,加工1000珍珠可以获得1粒种子"
 }
 ]
- 定义数据结构相关的类  1 
 2
 3
 4
 5package com.chenlvtang.student.pojo.entity; 
 //物品基础静态数据类
 public record PropTemplate(Number tId, String name, String desc) {
 }
- 读取配置文件并使用  1 
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50import com.chenlvtang.student.pojo.entity.PropTemplate; 
 import com.chenlvtang.student.service.PropTemplateService;
 import com.fasterxml.jackson.core.type.TypeReference;
 import com.fasterxml.jackson.databind.ObjectMapper;
 import jakarta.annotation.PostConstruct;
 import org.springframework.stereotype.Service;
 import java.io.IOException;
 import java.io.InputStream;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 /**
 * Created with IntelliJ IDEA.
 *
 * @author Administrator
 * Date: 2025/1/16
 * Time: 14:42
 * Description:物品静态数据服务实现类
 */
 public class PropTemplateServiceImpl implements PropTemplateService {
 private final Map<Number, PropTemplate> itemCache = new HashMap<>();
 private final ObjectMapper objectMapper;
 public PropTemplateServiceImpl(ObjectMapper objectMapper) {
 this.objectMapper = objectMapper;
 }
 
 public void loadItemsIntoCache() throws IOException {
 InputStream inputStream = getClass().getClassLoader().getResourceAsStream("Prop.json");
 if (inputStream == null) {
 throw new IOException("未发现 Prop.json 文件");
 }
 List<PropTemplate> itemList = objectMapper.readValue(inputStream, new TypeReference<>() {
 });
 for (PropTemplate item : itemList) {
 itemCache.put(item.tId(), item);
 }
 }
 
 public PropTemplate getPropTemplateById(int id) {
 return itemCache.get(id);
 }
 }
进一步完善:使用@Value传值
- 在application.properties中添加配置文件路径1 
 2
 3
 4### 这里都是自定义的 
 config:
 file-path:
 prop: Prop.json
- 在类中使用@Value注解获取配置文件路径1 
 2
 private String propFilePath;