【问题标题】:Alternate solution for @Conditional in Spring 3.1.1Spring 3.1.1 中 @Conditional 的替代解决方案
【发布时间】:2018-02-07 04:07:32
【问题描述】:

我被困在 Spring 3.1.1 应用程序中,无法升级到 4.x,因此我无法使用 @Conditional 注释有条件地启用 Spring Bean。在 Spring 3.1.1 中实现类似行为的最简单方法是什么?目前我没有使用 Profiles,而是希望实现一些更简单的东西。有什么建议吗?

编辑...进一步说明

我有一个 @Configuration 文件,其中包含我所有的 JMS 配置/Bean。我只想根据属性文件中的真/假属性加载此文件中的 bean。我需要能够根据属性文件打开或关闭此功能。在 Spring 4 中,添加了应用 @Conditional 注释并提供加载 bean 的条件的功能。我需要做同样的事情,但在 Spring 3.1.1 中。

【问题讨论】:

    标签: java spring spring-java-config


    【解决方案1】:

    如果你的属性设置了,那么创建你的bean怎么样,否则创建null?

    @Bean
    public YourBean yourBean(@Value("your.property.value") boolean enabled) {
        if (enabled) {
            return new YourBean();
        }
        return null;
    }
    

    这样它就不会在其他地方使用。 如果你需要自动装配,你可以自动装配它然后像:

    @Autowired(required = false)
    private YourBean someBean;
    

    并在使用前检查它是否存在。

    【讨论】:

    • 您的 bean 必须返回 Optional<YourBean> 的实例,而不是 null,因为如果它返回 null,那将失去意义。
    • @Makoto 请解释一下? Spring 自动处理 Optional<YourBean> 类型的依赖关系,以便它们仅在定义时可用。
    • 我不确定 Spring 3.x 是否会自动处理这个问题,因为 Optional 是 Java 8 附带的,而 Spring 3.x 仅支持 Java 7...
    • 啊,确实如此。那么必须使用 required = false 。已更新。
    猜你喜欢
    • 2011-04-13
    • 2016-10-24
    • 2020-08-29
    • 2016-04-30
    • 2017-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多