多个否定的配置文件

时间:2014-11-25 14:58:24

标签: java spring

我的问题是我有应用程序,它使用Spring配置文件。在服务器上构建应用程序意味着配置文件设置为“wo-data-init”。对于其他版本,有“test”个人资料。当它们中的任何一个被激活时,它们不应该运行Bean方法,所以我虽然这个注释应该可以工作:

@Profile({"!test","!wo-data-init"})

似乎更像是在运行if(!test OR !wo-data-init)而在我的情况下我需要它来运行if(!test AND !wo-data-init) - 它甚至可能吗?

3 个答案:

答案 0 :(得分:9)

Spring 4为conditional bean creation带来了一些很酷的功能。在您的情况下,确实纯@Profile注释是不够的,因为它使用OR运算符。

您可以执行的解决方案之一是为其创建自定义注释和自定义条件。例如

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@Documented
@Conditional(NoProfilesEnabledCondition.class)
public @interface NoProfilesEnabled {
    String[] value();
}
public class NoProfilesEnabledCondition implements Condition {

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        boolean matches = true;

        if (context.getEnvironment() != null) {
            MultiValueMap<String, Object> attrs = metadata.getAllAnnotationAttributes(NoProfileEnabled.class.getName());
            if (attrs != null) {
                for (Object value : attrs.get("value")) {
                    String[] requiredProfiles = (String[]) value;

                    for (String profile : requiredProfiles) {
                        if (context.getEnvironment().acceptsProfiles(profile)) {
                            matches = false;
                        }
                    }

                }
            }
        }
        return matches;
    }
}

以上是ProfileCondition的快速而肮脏的修改。

现在您可以通过以下方式注释您的bean:

@Component
@NoProfilesEnabled({"foo", "bar"})
class ProjectRepositoryImpl implements ProjectRepository { ... }

答案 1 :(得分:0)

我找到了更好的解决方案

@Profile("default")

配置文件默认表示没有foo和栏配置文件。

答案 2 :(得分:0)

在Spring 5.1(Spring Boot 2.1)及更高版本中,它很简单:

@Component
@Profile("!a & !b")
public class MyComponent {}

参考:How to conditionally declare Bean when multiple profiles are not active?

相关问题