java - 如何从 Condition Autowiring 属性 bean

标签 java spring initialization conditional-statements autowired

有没有办法在 Condition 中 Autowiring bean?

还有下一个例子。我们有 2 个 FileManager 的实现。其中一个实现应该根据属性“平台”进行初始化。通过 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 之前初始化它?

最佳答案

如果我们看一下java docs对于 Condition界面-

Conditions must follow the same restrictions as BeanFactoryPostProcessor and take care to never interact with bean instances.

限制是(java docsBeanFactoryPostProcessor )

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.

所以您要实现的目标是不推荐;已经遇到的副作用。

但是,如果我们在文档中进一步挖掘 Condition我们得到

For more fine-grained control of conditions that interact with @Configuration beans consider the ConfigurationCondition interface.

这里也违反了限制。因此,总而言之,使用 Condition在这种情况下不是一个好主意。

所以 IMO 对你来说最好的选择是使用 @Profile您可以在其中一次激活所需的配置文件并使用相应的 bean;不考虑附加的装饰。

关于java - 如何从 Condition Autowiring 属性 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28556627/

相关文章:

java - bean 类型 java.util.Properties 的不满足依赖异常

java - Hibernate 关系加载

java - propertiesfactorybean vs propertyplaceholderconfigurer spring?

c++ - 某些变量初始化中的 "l"是什么意思 - C++

java - 为什么java不与静态外部字段同时初始化静态嵌套类字段?

java - getChildren() add() 和 add()

java - 如何使 Sublime Text 3 在 Ubuntu 上通过终端编译和运行 java

c - 初始化 "a pointer to an array of integers"

java - JAXB:将具有不同属性的多个元素解码到同一 java 类中的单独字段中

java - Facebook 登录 加载用户资料