我有從多個來源收集信息的應用程序配置對象 - .properties文件,數據庫表,操作系統,等等 - 使得這個提供給應用程序的其餘部分,如果他們java.util.Properties
,例如:我可以將靜態方法註冊爲Guava EventBus訂戶嗎?
private static String devToAddress = Config.getConfig().getProperty("testAddress");
這些經常被存儲,如上所示,作爲一個靜態的,所以它總是可用於一個類的所有實例,而無需不斷地獲取它。
我也有辦法告訴這個(網絡)應用程序重新加載這些「屬性」,所以我可以重新配置應用程序,而不需要重新啓動運行。
我想要做的就是註冊我的Guava EventBus來訂閱我的「ConfigurationChangeEvent」,這樣當我使用我的重新加載功能時,班級可以更新這個。 在某些情況下,這可能是一個只有靜態方法的靜態類,它仍然需要應用程序配置信息,所以我不一定指望有一個實例來完成更新靜態變量的工作。
我想這是什麼:
package com.sample.mw;
import com.google.common.eventbus.Subscribe;
import com.example.mw.events.ConfigurationChangeEvent;
import com.example.mw.events.EventDispatcher;
import com.example.mw.Config;
public class SampleMailer
{
private static String devToAddress;
// constructor(s)
public SampleMailer()
{
// ...
}
// instance methods
// ...
// static methods
public static String getTheAddress()
{
return devToAddress;
}
@Subscribe
public static void loadConfig(ConfigurationChangeEvent cce)
{
devToAddress = Config.getConfig().getProperty("testAddress");
}
// static/class registration with the event bus
static
{
loadConfig(null); // initial config load without an event
// 'EventDispatcher' is my singleton that encapsulates the EventBus
EventDispatcher.getDispatcher().register(SampleMailer.class); // <-- not sure what to register here
}
}
的問題是(A)這是可能的呢?你能靜態註冊Guava EventBus嗎? (b)什麼對象我會傳遞給EventBus .register(Object object)
方法嗎?
呃,你爲什麼不創建一個單身呢? – fge
簡短的回答是:不。一個'Class'對象不能以這種方式工作。這將是很好,對稱,但有些語言可以工作。不過,我很害怕。 – biziclop