[英]How to autowire properties bean from Condition
有沒有辦法在條件下自動裝配bean?
還有一個例子。 我們有2個FileManager的實現。 其中一個實現應該初始化取決於屬性'platform'。 屬性通過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 {
...
}
此代碼不起作用。 主要原因是因為條件匹配時ArchaiusProperties bean沒有初始化。 有沒有辦法在條件下使用它之前初始化ArchaiusProperties bean?
如果我們看看Condition
接口的java文檔 -
條件必須遵循與
BeanFactoryPostProcessor
相同的限制,並注意永遠不要與bean實例交互。
限制是( 來自BeanFactoryPostProcessor
java文檔 )
BeanFactoryPostProcessor
可以與bean定義交互並修改bean定義,但絕不能與 bean實例交互。 這樣做可能會導致bean過早實例化,違反容器並導致意外的副作用。
所以你想要實現的是不推薦的東西; 已經遇到的副作用。
但是,如果我們進一步深入了解Condition
文檔,我們得到
要更好地控制與@Configuration bean交互的條件,請考慮
ConfigurationCondition
接口。
這里的限制也違反了。 因此,在這種情況下使用Condition
總而言之並不是一個好主意。
所以IMO最適合你的是使用@Profile ,你可以一次激活所需的配置文件並使用相應的bean; 沒有考慮附加的裝飾。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.