几条固定数据需要建表?

在开发中,可能会遇到这样的业务场景:已知有几条固定的数据,需要实现【展示&修改】功能。
建表? 杀鸡用牛刀
缓存? 服务器重启,数据就失效了


从领域角度而言,这种数据可以视为配置(config),使用者可以选择自己想要的某种配置,同时又可以对这些配置做出一定调整(修改)。
谈到配置,不难想出用配置文件的方式来管理这些数据,以下代码为具体实现。

xxxx\conf\config.properties
代码会自动在这个路径创建一个名为config.properties的文件,其中就可以存储你想要的各种配置,每个配置设定相应的key,根据getValue()方法读取key对应的value,setValue()方法修改key对应的value


点击查看代码
/**
 * 配置文件助手
 * 专注于处理配置文件的业务
 */
@Component
public class ConfigHelper {

    private final Properties props = new Properties();

    /**
     * 配置文件名
     */
    public static final String CONFIG_FILENAME = "config.properties";

    /**
     * 门禁配置的key
     */
    public static final String ENTRANCE_KEY = "entrance.guard";

    /**
     * 配置文件路径
     */
    private Path configFilePath;

    @Value("${服务器可编辑权限文件夹根路径}")
    private String root;

    /**
     * 读取配置项的值
     *
     * @param key 配置项的键
     * @return 配置项的值
     */
    public String getValue(String key) throws IOException {
        loadProperties();
        return props.getProperty(key);
    }

    /**
     * 修改配置项的值
     *
     * @param key   配置项的键
     * @param value 配置项的值
     */
    public void setValue(String key, String value) throws IOException {
        loadProperties();
        props.setProperty(key, value);
        saveProperties();
    }

    /**
     * 加载配置文件
     */
    private void loadProperties() throws IOException {
        configFilePath = Paths.get(root, "conf", CONFIG_FILENAME);
        if (!Files.exists(configFilePath)) {
            createConfigFile();
        }
        try (InputStream inputStream = Files.newInputStream(configFilePath)) {
            props.load(inputStream);
        }
    }

    /**
     * 保存配置文件
     */
    private void saveProperties() throws IOException {
        try (OutputStream outputStream = Files.newOutputStream(configFilePath)) {
            props.store(outputStream, null);
        }
    }

    /**
     * 创建新的配置文件
     */
    private void createConfigFile() throws IOException {
        Path dirPath = Paths.get(root, "conf");
        Files.createDirectories(dirPath);
        configFilePath = dirPath.resolve(CONFIG_FILENAME);
        try (OutputStream outputStream = Files.newOutputStream(configFilePath)) {
            props.store(outputStream, null);
        }
    }
}
posted @ 2023-05-13 14:54  Ashe|||^_^  阅读(25)  评论(0编辑  收藏  举报