Spring Boot 加载配置文件信息

参考

加载配置文件信息使用场景

  • 游戏物品等策划配置的表格数据,如游戏物品名称,物品描述,物品图标等不会经常变动的数据,可以放在配置文件里,通过配置文件加载到内存中,减少数据库查询次数,提高性能。

配置文件加载方式

  1. 将表格获取其他数据的配置文件放在resources目录下。
  2. 定义数据结构相关的类
  3. 读取配置文件并使用

代码示例

  1. 将文件放在resources目录下,如src/main/resources/Prop.json
    1
    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粒种子"
    }
    ]
  2. 定义数据结构相关的类
    1
    2
    3
    4
    5
    package com.chenlvtang.student.pojo.entity;

    //物品基础静态数据类
    public record PropTemplate(Number tId, String name, String desc) {
    }
  3. 读取配置文件并使用
    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
    50
    import 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:物品静态数据服务实现类
    */
    @Service
    public class PropTemplateServiceImpl implements PropTemplateService {
    private final Map<Number, PropTemplate> itemCache = new HashMap<>();

    private final ObjectMapper objectMapper;

    public PropTemplateServiceImpl(ObjectMapper objectMapper) {
    this.objectMapper = objectMapper;
    }

    @PostConstruct
    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);
    }
    }

    @Override
    public PropTemplate getPropTemplateById(int id) {
    return itemCache.get(id);
    }
    }

进一步完善:使用@Value传值

  1. 在application.properties中添加配置文件路径
    1
    2
    3
    4
    ### 这里都是自定义的
    config:
    file-path:
    prop: Prop.json
  2. 在类中使用@Value注解获取配置文件路径
    1
    2
    @Value("${config.file-path.prop}")
    private String propFilePath;