有没有办法在条件下自动装配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?
Conditions must follow the same restrictions as
beanfactoryPostProcessor
and take care to never interact with bean instances.
限制是(从beanfactoryPostProcessor的java docs开始)
A
beanfactoryPostProcessor
may interact with and modify bean definitions,but never bean instances. Doing so may cause premature bean instantiation,violating the container and causing unintended side-effects.
所以你想要实现的是不推荐的东西;已经遇到的副作用.
但是,如果我们进一步深入了解条件的文档,我们得到
For more fine-grained control of conditions that interact with @Configuration beans consider the
ConfigurationCondition
interface.
这里的限制也违反了.因此,在这种情况下使用Condition总而言之并不是一个好主意.