从多个类访问Java配置
我正在探索用Java进行简单、简单的基于文件的配置的方法。我研究了Java的内置从多个类访问Java配置,java,oop,configuration,apache-commons-config,Java,Oop,Configuration,Apache Commons Config,我正在探索用Java进行简单、简单的基于文件的配置的方法。我研究了Java的内置属性和Apache公共配置库。对于后者,提取的代码如下所示: Configurations configs = new Configurations(); Configuration config = null; try { config = configs.properties(new File("config.properties")); } catch (ConfigurationException c
属性
和Apache公共配置库。对于后者,提取的代码如下所示:
Configurations configs = new Configurations();
Configuration config = null;
try
{
config = configs.properties(new File("config.properties"));
}
catch (ConfigurationException cex)
{
}
long loadQPS = config.getInt("loadQPS");
我遇到的问题是,我发现自己在每个类中都插入了这个,这是次优的,至少有两个原因:1)我在每个类中读取一次文件,而我应该只读取一次。2) 代码重复
一个显而易见的解决方案是创建一个单例配置类,然后从其他每个类访问该类。但这肯定是几乎所有用例中都需要的特性,所以它不应该包含在配置库中吗(我遗漏了什么吗)?我还考虑过使用SpringConfiguration,它可以为我创建一个单例配置类,但是仅仅基于文件的配置不会有太多开销吗?(据我所知,春天的力量在于DI。)
什么是好的解决方案或最佳实践(如果有)
编辑:答案中建议的简单静态解决方案:
public class ConfigClass {
static Configuration config;
static {
Configurations configs = new Configurations();
Logger sysLogger = LoggerFactory.getLogger("sysLogger");
try
{
config = configs.properties(new File("config.properties"));
}
catch (ConfigurationException cex)
{
sysLogger.error("Config file read error");
}
}
}
通过
ConfigClass.config
访问包中的内容,因此您有两个选项。一个简单的方法是静态存储和访问配置对象
当我希望在没有Spring的情况下进行依赖注入时,我喜欢的另一个方法是以DI友好的方式构造程序。您可以通过将main()函数转换为最终启动它的程序的“配置”来模拟DI容器
考虑一个典型的多层web应用程序:DI友好的main()方法可能如下所示:
public class AddressBookApp {
public static void main(String[] args) {
Configuration conf = new Configuration(args[0]);
// Creates our Repository, this might do some internal JDBC initialization
AddressBookRepository repo = new AddressBookRepository(conf);
// Pass the Repository to our Service object so that it can persist data
AddressBookService service = new AddressBookService(repo);
// Pass the Service to the web controller so it can invoke business logic
AddressBookController controller = new AddressBookController(conf, service);
// Now launch it!
new WebApp(new Controller[] { controller }).start();
}
}
main()是“连接”应用程序的中心位置,因此可以很容易地将配置对象传递给每个需要它的组件 另外,另请注意,
Configuration config=null代码>似乎不是很优雅。欢迎提出建议!谢谢我决定现在使用简单的静态字段-将我的代码附加到上面的问题。