微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何从Condition自动装配属性bean

有没有办法在条件下自动装配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?

最佳答案
如果我们看一下java docs的Condition界面 –

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总而言之并不是一个好主意.

所以IMO最适合你的是@Profile,你可以一次激活所需的配置文件并使用相应的bean;没有考虑附加的装饰.

原文地址:https://www.jb51.cc/spring/432452.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐