[英]How can I inject a property which is dependent upon another value in Guice 4.1?
我有一個被多個模塊使用的服務,並且在每個模塊中,它定義了自己的提供程序來提供依賴於另一個值的值。 與其在該對象中擁有所有其他值,不如直接使用該單個值,但無法將Guice的bindConstant()應用於提供程序。
當前的偽代碼:
ConfigurationProvider implements Provider<Configuration> {
final Configuration configuration;
@Inject
public ConfigurationProvider(BuildConfiguration buildConfiguration) {
configuration = new Configuration();
configuration.setDownloadPath(buildConfiguration.getBuildPath() + File.separator + "downloads");
}
public Configuration get() {
return configuration;
}
}
在模塊內部:
bind(Configuration.class).toProvider(ConfigurationProvider.class);
相反,我想在可能的地方使用屬性注入,然后執行以下操作:
DownloadPathProvider implements Provider<Property<DownloadPath, String>> {
final String downloadPath;
@Inject public DownloadPathProvider(BuildConfiguration buildConfiguration) {
downloadPath = buildConfiguration.getBuildPath() + File.separator + "downloads";
}
public String get() {
return downloadPath;
}
}
我相信問題在於,為了使bindConstant正常工作,我需要在初始化模塊時已經確定該值。 但是這種情況下的值是稍后(實際上是通過另一個提供程序)得出的。
盡管可以將配置放入一個簡單的pojo中,但我覺得直接將其與該屬性嵌套在一起要比將其嵌套在pojo中更為簡潔。
配置或值實際上是一個常數,因為一旦設置,它就永遠不會改變。 我只想將該值作為另一個值的基礎。
如果此值在模塊創建時未固定,則不是常數。 它實際上是一個單例。 除了使用bindConstant()
,還可以使用bind().in(Scope.Singleton)
。
由於我希望能夠直接注入基本類型,因此我不得不發揮創造力...
在運行時,屬性源按順序運行,計算后的屬性最后運行。
這有點駭人聽聞,我將看看是否可以多清理一點,然后發布代碼以使其正常工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.