编写整个框架的目的是为了处理应用程序的配置。 我更喜欢一种简单的方法。
如果通过配置我们的意思是“ 部署之间可能有所不同的所有内容 ”,那么我们应该尝试使配置保持简单。 在Java中,最简单的选项是不起眼的属性文件。 属性文件的缺点是,当您希望应用程序接收更改时必须重新启动它。 还是你
这是我在多个项目中使用的一种简单方法:
public class MyAppConfig extends AppConfiguration {
private static MyAppConfig instance = new MyAppConfig();
public static MyAppConfig instance() {
return instance;
}
private MyAppConfig() {
this("myapp.properties");
}
public String getServiceUrl() {
return getRequiredProperty("service.url");
}
public boolean getShouldStartSlow() {
return getFlag("start-slow", false);
}
public int getHttpPort(int defaultPort) {
return getIntProperty("myapp.http.port", defaultPort);
}
}
AppConfiguration类如下所示:
public abstract class AppConfiguration {
private static Logger log = LoggerFactory.getLogger(AppConfiguration.class);
private long nextCheckTime = 0;
private long lastLoadTime = 0;
private Properties properties = new Properties();
private final File configFile;
protected AppConfiguration(String filename) {
this.configFile = new File(filename);
}
public String getProperty(String propertyName, String defaultValue) {
String result = getProperty(propertyName);
if (result == null) {
log.trace("Missing property {} in {}", propertyName, properties.keySet());
return defaultValue;
}
return result;
}
public String getRequiredProperty(String propertyName) {
String result = getProperty(propertyName);
if (result == null) {
throw new RuntimeException("Missing property " + propertyName);
}
return result;
}
private String getProperty(String propertyName) {
if (System.getProperty(propertyName) != null) {
log.trace("Reading {} from system properties", propertyName);
return System.getProperty(propertyName);
}
if (System.getenv(propertyName.replace('.', '_')) != null) {
log.trace("Reading {} from environment", propertyName);
return System.getenv(propertyName.replace('.', '_'));
}
ensureConfigurationIsFresh();
return properties.getProperty(propertyName);
}
private synchronized void ensureConfigurationIsFresh() {
if (System.currentTimeMillis() < nextCheckTime) return;
nextCheckTime = System.currentTimeMillis() + 10000;
log.trace("Rechecking {}", configFile);
if (!configFile.exists()) {
log.error("Missing configuration file {}", configFile);
}
if (lastLoadTime >= configFile.lastModified()) return;
lastLoadTime = configFile.lastModified();
log.debug("Reloading {}", configFile);
try (FileInputStream inputStream = new FileInputStream(configFile)) {
properties.clear();
properties.load(inputStream);
} catch (IOException e) {
throw new RuntimeException("Failed to load " + configFile, e);
}
}
}
这样可以高效地读取配置文件,并根据需要更新设置。 它支持默认的环境变量和系统属性。 而且它甚至可以很好地记录正在发生的事情。
- 有关完整的源代码和自动更新的不可思议的数据源,请参见以下要点:https://gist.github.com/jhannes/b8b143e0e5b287d73038
请享用!
翻译自: https://www.javacodegeeks.com/2014/10/dead-simple-configuration.html