test.yml
key1: value1
key2: value2
key3: value3
PropertiesUtils
import cn.hutool.core.io.FileUtil;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
public class PropertiesUtils {
private static final Logger logger = LoggerFactory.getLogger(PropertiesUtils.class);
public Properties properties;
public PropertiesUtils(String... resourcesPaths) {
load(resourcesPaths);
}
private void load(String[] resourcesPaths) {
properties = new Properties();
for (String location : resourcesPaths) {
InputStreamReader is = null;
try {
is = new InputStreamReader(getClass().getResourceAsStream("/" + location), StandardCharsets.UTF_8);
properties.load(is);
} catch (Exception ex) {
logger.error("Could not load properties from path:" + location + ", " + ex.getMessage());
} finally {
IOUtils.closeQuietly(is);
}
}
}
public Object getValue(String key) {
if (properties.containsKey(key)) {
return properties.getProperty(key);
}
return "";
}
public String getAbsolutePath(String filename) throws URISyntaxException {
if (!FileUtil.isAbsolutePath(filename)) {
filename = PropertiesUtils.class.getClassLoader().getResource(filename).toURI().getPath();
}
return filename;
}
}
TestUtil
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
@Component
public class TestUtil {
public static Map<String, String> testMap = new HashMap<>();
@PostConstruct
public void init(){
long startTime = System.currentTimeMillis();
PropertiesUtils properties = new PropertiesUtils("test.yml");
for (Map.Entry<Object, Object> entry : properties.properties.entrySet()) {
Object key = entry.getKey();
Object value = entry.getValue();
testMap.put(key.toString(), value.toString());
}
System.out.println("load time :" + (System.currentTimeMillis() - startTime) + "ms");
}
}