Spring:如何在Profiles中做AND? [英] Spring: How to do AND in Profiles?

查看:113
本文介绍了Spring:如何在Profiles中做AND?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Spring Profile 注释可以让你选择配置文件。但是,如果您阅读文档,它只允许您使用OR操作选择多个配置文件。如果您指定@Profile(A,B),那么如果配置文件A或配置文件B处于活动状态,您的bean将会启动。

Spring Profile annotation allows you to select profiles. However if you read documentation it only allows you to select more than one profile with OR operation. If you specify @Profile("A", "B") then your bean will be up if either profile A or profile B is active.

我们的用例不同我们希望支持多种配置的TEST和PROD版本。因此,有时我们只想在两个配置文件TEST和CONFIG1都处于活动状态时自动装配bean。

Our use case is different we want to support TEST and PROD versions of multiple configurations. Therefore sometimes we want to autowire the bean only if both profiles TEST and CONFIG1 are active.

有没有办法用Spring做到这一点?什么是最简单的方法?

Is there any way to do it with Spring? What would be the simplest way?

推荐答案

由于Spring不提供开箱即用的AND功能。我建议采用以下策略:

Since Spring does not provide the AND feature out of the box. I would suggest the following strategy:

目前 @Profile 注释具有条件注释 @条件(ProfileCondition.class)。在 ProfileCondition.class 中,它遍历配置文件并检查配置文件是否处于活动状态。类似地,您可以创建自己的条件实现并限制注册bean。例如

Currently @Profile annotation has a conditional annotation @Conditional(ProfileCondition.class). In ProfileCondition.class it iterates through the profiles and checks if the profile is active. Similarly you could create your own conditional implementation and restrict registering the bean. e.g.

public class MyProfileCondition implements Condition {

    @Override
    public boolean matches(final ConditionContext context,
            final AnnotatedTypeMetadata metadata) {
        if (context.getEnvironment() != null) {
            final MultiValueMap<String, Object> attrs = metadata.getAllAnnotationAttributes(Profile.class.getName());
            if (attrs != null) {
                for (final Object value : attrs.get("value")) {
                    final String activeProfiles = context.getEnvironment().getProperty("spring.profiles.active");

                    for (final String profile : (String[]) value) {
                        if (!activeProfiles.contains(profile)) {
                            return false;
                        }
                    }
                }
                return true;
            }
        }
        return true;
    }

}

在你班上:

@Component
@Profile("dev")
@Conditional(value = { MyProfileCondition.class })
public class DevDatasourceConfig

注意:我没有检查所有角落情况(如null,长度检查等)。但是,这个方向可能有所帮助。

NOTE: I have not checked for all the corner cases (like null, length checks etc). But, this direction could help.

这篇关于Spring:如何在Profiles中做AND?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆