多个否定的配置文件

2022-09-02 20:28:48

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

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

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


答案 1

在Spring 5.1.4(Spring Boot 2.1.2)及更高版本中,它就像这样简单:

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

Ref:当多个配置文件不活动时,如何有条件地声明Bean?


答案 2

Spring 4为有条件的Bean创建带来了一些很酷的功能。在你的例子中,实际上普通的注释是不够的,因为它使用运算符。@ProfileOR

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

@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;
    }
}

以上是配置文件条件的快速和肮脏的修改。

现在,您可以通过以下方式注释您的豆子:

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

推荐