如何:在Spring中使用@Conditional和Condition注册组件

Spring中的@Profile批注可以用于任何自动检测候选的Spring组件(例如, @Service Component, @Service @Component@Service @Configuration等)。 @Profile批注接受单个配置文件或一组必须是活动的配置文件,以使带注释的组件有资格进行自动检测。 对于给定的@Profile({"p1", "!p2"}) ,如果配置文件p1处于活动状态配置文件p2不处于活动状态,则会进行注册。 至关重要。

但是如何使用@Profile来实现这一点:如果配置文件p1处于活动状态并且配置文件p2 p3均处于非活动状态,我们想激活给定的组件吗?

让我们假设以下情况:我们有一个NotificationSender接口,该接口由以下方式实现:

  • SendGridNotificationSender –仅在sendgrid配置文件处于活动状态时才处于活动状态,
  • EmailNotificationSender –仅在email配置文件处于活动状态时才处于活动状态。
  • NoOpNotificationSender –仅在development配置文件处于活动状态且sendgridemail没有处于活动状态时才处于活动状态。

另外:一次只能注册一个NotificationSender ,并且development配置文件可以与sendgridemail配置文件结合使用。

在上述情况下,使用@Profile批注似乎还不够。 也许我使事情变得有些复杂,但是实际上我真的很想实现上述目标而无需介绍其他配置文件。 我是怎么做到的?

我使用了Spring的4 @Conditional批注。 当所有指定Condition匹配时, @Conditional允许注册组件:

@Component
@Conditional(value = NoOpNotificationSender.ProfilesCondition.class)
class NoOpNotificationSender extends NotificationSenderAdapter {

}

ProfilesCondition实现org.springframework.context.annotation.Condition接口:

public static class ProfilesCondition implements Condition {
    @Override
    public boolean matches(ConditionContext c, AnnotatedTypeMetadata m) {

    }
}

问题的整体解决方案:

@Component
@Conditional(value = NoOpNotificationSender.ProfilesCondition.class)
class NoOpNotificationSender extends NotificationSenderAdapter {

    static class ProfilesCondition implements Condition {
        @Override
        public boolean matches(ConditionContext c, AnnotatedTypeMetadata m) {
            return accepts(c, Profiles.DEVELOPMENT)
                && !accepts(c, Profiles.MAIL)
                && !accepts(c, Profiles.SEND_GRID);
        }

        private boolean accepts(ConditionContext c, String profile) {
            return c.getEnvironment().acceptsProfiles(profile);
        }
    }
}

当适当的配置文件处于活动状态时,其他组件将被激活:

@Component
@Profile(value = Profiles.SEND_GRID)
public class SendGridNotificationSender extends NotificationSenderAdapter {

}

@Component
@Profile(value = Profiles.MAIL)
class EmailNotificationSender extends NotificationSenderAdapter {

}

用法示例:

活动资​​料
发展 NoOpNotificationSender
开发,sendgrid SendGridNotificationSender
开发,邮件 EmailNotificationSender
sendgrid SendGridNotificationSender
邮件 EmailNotificationSender


你怎么看? 您将如何解决这个问题?

翻译自: https://www.javacodegeeks.com/2015/11/register-components-using-conditional-condition-spring.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值