本文介紹了如何從條件自動綁定屬性Bean的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
有沒有辦法自動布線處于正常狀態(tài)的Bean?
還有一個例子。我們有2個文件管理器的實(shí)現(xiàn)。其中一個實(shí)現(xiàn)應(yīng)該根據(jù)屬性‘Platform’在中進(jìn)行初始化。通過Archaius的屬性句柄。
@Component
public class AwsPlatformCondition implements Condition {
@Autowired
private ArchaiusProperties archaiusProperties;
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
return "aws".equalsIgnoreCase(archaiusProperties.getStringProperty(PropertiesMapper.PLATFORM));
}
}
。
@Component
public class StandardPlatformCondition implements Condition {
@Autowired
private ArchaiusProperties archaiusProperties;
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
return "standard".equalsIgnoreCase(archaiusProperties.getStringProperty(PropertiesMapper.PLATFORM));
}
}
。
@Component
@Conditional(AwsPlatformCondition.class)
public class AS3FileManager implements FileManager {
...
}
。
@Component
@Conditional(StandardPlatformCondition.class)
public class NativeFileManager implements FileManager {
...
}
此代碼不起作用。主要原因是當(dāng)條件匹配時,ArchaiusProperties Bean不會初始化。有什么方法可以在條件下使用ArchaiusProperties Bean之前對其進(jìn)行初始化嗎?
推薦答案
如果我們查看java docsCondition接口-
條件必須遵循與
BeanFactoryPostProcessor相同的限制,并且注意不要與Bean實(shí)例交互。
限制是(來自java docs,共BeanFactoryPostProcessor)
A
BeanFactoryPostProcessor可以與Bean定義交互并對其進(jìn)行修改,但絕不能Bean實(shí)例。這樣做可能會導(dǎo)致Bean過早實(shí)例化,從而破壞容器并導(dǎo)致意外的副作用。
因此,您嘗試實(shí)現(xiàn)的是不推薦的;其副作用已經(jīng)出現(xiàn)。
但是,如果我們在文檔中進(jìn)一步搜索Condition,我們會得到
有關(guān)與@ConfigurationBean交互的條件的更細(xì)粒度控制,請考慮
ConfigurationCondition接口。
此處也違反了限制。因此,總而言之,在此方案中使用Condition不是一個好主意。
因此,對于您來說,最好的選擇是使用@Profile,其中您可以一次激活所需的配置文件并使用相應(yīng)的Bean;而不考慮所附的裝飾。
這篇關(guān)于如何從條件自動綁定屬性Bean的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,






