wu
2024-11-12 fa6bebf3478bbea5c570851de91acf40fc40bbc4
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
package com.example.springboot.component;
 
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
 
// Configuration 类用于加载配置文件并提供访问配置项的方法。
public class Configuration {
    private Properties properties; // Properties 对象,用于存储配置文件中的键值对。
 
    // 构造函数,根据传入的文件名加载配置文件。
    public Configuration(String fileName) throws IOException {
        // 使用类加载器获取资源文件的输入流。
        InputStream inputStream = getClass().getClassLoader().getResourceAsStream(fileName);
        // 如果输入流为null,表示未找到文件,抛出FileNotFoundException。
        if (inputStream == null) {
            throw new FileNotFoundException("Property file '" + fileName + "' not found in the classpath");
        }
        properties = new Properties(); // 实例化Properties对象。
        properties.load(inputStream); // 从输入流加载配置项。
    }
 
    // 根据配置项的键获取其对应的值。
    public String getProperty(String key) {
        return properties.getProperty(key);
    }
}