com.feingto.cloud.kit.PropertiesLoader Maven / Gradle / Ivy
package com.feingto.cloud.kit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import java.io.IOException;
import java.io.InputStream;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Properties;
/**
* Properties文件载入工具类
*
* @author longfei
*/
@Slf4j
public class PropertiesLoader {
private static ResourceLoader resourceLoader = new DefaultResourceLoader();
private final Properties properties;
public PropertiesLoader(String... resourcesPaths) {
properties = loadProperties(resourcesPaths);
}
public Properties getProperties() {
return properties;
}
private String getValue(String key) {
String systemProperty = System.getProperty(key);
if (Objects.nonNull(systemProperty)) {
return systemProperty;
}
return properties.getProperty(key);
}
public String getProperty(String key) {
String value = getValue(key);
if (Objects.isNull(value)) {
throw new NoSuchElementException();
}
return value;
}
public String getProperty(String key, String defaultValue) {
String value = getValue(key);
return Objects.nonNull(value) ? value : defaultValue;
}
public Integer getInteger(String key) {
String value = getValue(key);
if (Objects.isNull(value)) {
throw new NoSuchElementException();
}
return Integer.valueOf(value);
}
public Integer getInteger(String key, Integer defaultValue) {
String value = getValue(key);
return Objects.nonNull(value) ? Integer.valueOf(value) : defaultValue;
}
public Double getDouble(String key) {
String value = getValue(key);
if (Objects.isNull(value)) {
throw new NoSuchElementException();
}
return Double.valueOf(value);
}
public Double getDouble(String key, Integer defaultValue) {
String value = getValue(key);
return Objects.nonNull(value) ? Double.valueOf(value) : defaultValue;
}
public Boolean getBoolean(String key) {
String value = getValue(key);
if (Objects.isNull(value)) {
throw new NoSuchElementException();
}
return Boolean.valueOf(value);
}
public Boolean getBoolean(String key, boolean defaultValue) {
String value = getValue(key);
return Objects.nonNull(value) ? Boolean.valueOf(value) : defaultValue;
}
/**
* 载入多个文件, 文件路径使用Spring Resource格式
*/
private Properties loadProperties(String... resourcesPaths) {
Properties props = new Properties();
for (String location : resourcesPaths) {
log.debug("Loading properties file from path: {}", location);
InputStream is = null;
try {
Resource resource = resourceLoader.getResource(location);
is = resource.getInputStream();
props.load(is);
} catch (IOException ex) {
log.info("Could not load properties from path: {}, {} ", location, ex.getMessage());
} finally {
try {
if (Objects.nonNull(is)) is.close();
} catch (IOException ignored) {
}
}
}
return props;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy