【问题标题】:How to make a bean configuration trigger only when two profiles are active如何仅在两个配置文件处于活动状态时触发 bean 配置
【发布时间】:2014-06-19 10:27:27
【问题描述】:

我有一个 bean,只有当两个配置文件“demo”和“local”都处于活动状态时才应该创建它。在基于 java 的 Spring 配置中实现这一目标的最佳方法是什么。

到目前为止,我想出的是,创建如下 bean:

@Profile("demo")
@Bean("isDemoActive")
public Boolean isDemoActive(){ return true;}

然后将那些注入到 bean 创建方法中并对这些 bean 执行 if 条件。

有没有更好/更简单的方法来做这种事情?

【问题讨论】:

  • 我认为你需要使用@Conditional注解来定义你自己的匹配规则。在实现Condition 的课程中​​,您可以使用context.getEnvironment().getActiveProfiles() 访问活动配置文件。在那里你检查哪些是活动的并返回truefalse

标签: spring spring-java-config spring-profiles


【解决方案1】:

这是我的建议,根据我上面的评论:

import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;

public class DoubleProfilesCondition implements Condition {
    public boolean matches(ConditionContext context,AnnotatedTypeMetadata metadata) {

        String[] activeProfiles = context.getEnvironment().getActiveProfiles();

        int counter = 0;
        for (int i = 0; i < activeProfiles.length; i++) {
            String profile = activeProfiles[i];
            if (profile.equals("profile1") || profile.equals("profile2")) {
                counter++;
            }
        }

        if (counter == 2)
            return true;
        return false;
   }
}

以及决定创建哪些 bean 的类:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;

@Configuration
@Conditional(DoubleProfilesCondition.class)
public class MyConfig {

    public @Bean
    ExampleService service() {
        ExampleService service = new ExampleService();
        service.setMessage("hello, success!");
        return service;
    }
}

【讨论】:

  • 酷。不知道条件语句!
  • Here's相关参考文档。
  • 实际上并没有实现它,但我把方法放在了我的工具箱中。
【解决方案2】:

我编写了一个@ProfileAll 注释,它与标准的@Profile 注释非常相似,但是如果ALL,则只有spring 才会处理带注释的配置、方法... > 给定的配置文件当前处于活动状态:

ProfileAll.java(注解)

import org.springframework.context.annotation.Conditional;

@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
@Documented
@Conditional(ProfileAllCondition.class)
public @interface ProfileAll {

    /** The set of profiles for which the annotated component should be registered. */
    String[] value();

}

ProfileAllCondition.java(条件)

import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.util.MultiValueMap;

class ProfileAllCondition implements Condition {

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        if (context.getEnvironment() != null) {
            MultiValueMap<String, Object> attrs = metadata.getAllAnnotationAttributes(ProfileAll.class.getName());
            if (attrs != null) {
                LinkedList<String> profilesActive = new LinkedList<>();
                LinkedList<String> profilesNotActive = new LinkedList<>();
                List<Object> values = attrs.get("value");
                int count = 0;
                for (Object value : values) {
                    for (String profile : ((String[]) value)) {
                        count++;
                        if (context.getEnvironment().acceptsProfiles(profile)) {
                            profilesActive.add(profile);
                        } else {
                            profilesNotActive.add(profile);
                        }
                    }
                }
                if (profilesActive.size() == count) {
                    return true;
                } else {
                    return false;
                }
            }
        }
        return true;
    }
}

如下使用,例如:

@Profile({ "mysql", "cloud", "special" })
@Configuration
public class MySqlConfig {
...

只有在所有三个配置文件当前在启动时都处于活动状态时,才会处理 MySqlConfig。

【讨论】:

    猜你喜欢
    • 2023-03-26
    • 1970-01-01
    • 2011-07-15
    • 2013-10-03
    • 2016-01-06
    • 2017-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多