4

我可以使用@AutowiredSpring 4.x @Components@ConditionalOnProperty来选择基于featuretoggles.properties文件的功能实现吗?

public class Controller {
  @Autowired
  private Feature feature;
}

@Component
@ConditionalOnProperty(name = "b", havingValue = "off")
public class A implements Feature {
}

@Component
@ConditionalOnProperty(name = "b", havingValue = "on")
public class B implements Feature {
}

@Configuration
@PropertySource("classpath:featuretoggles.properties")
public class SomeRandomConfig {
}

使用src/main/resources/featuretoggles.properties文件:

b = on

(切换器“b”的名称和类“B”匹配的名称是巧合;让它们相等不是我的目标,切换器可以有任何名称。)

这无法featureControllerwith中自动连接UnsatisfiedDependencyException,说“没有可用的‘功能’类型的合格 bean:预计至少有 1 个有资格作为自动装配候选者的 bean”。

我知道我可以通过一个根据属性@Configuration选择 a 的类来实现这一点。@Bean但是当我这样做时,我必须在每次添加功能切换时添加一个新的配置类,并且这些配置类将非常相似:

@Configuration
@PropertySource("classpath:featuretoggles.properties")
public class FeatureConfig {

    @Bean
    @ConditionalOnProperty(name = "b", havingValue = "on")
    public Feature useB() {
        return new B();
    }

    @Bean
    @ConditionalOnProperty(name = "b", havingValue = "off")
    public Feature useA() {
        return new A();
    }

}
4

1 回答 1

2

我按照本指南做了你想做的事情。第一步是写一个Condition...

public class OnEnvironmentPropertyCondition implements Condition
{
  @Override
  public boolean matches(ConditionContext ctx, AnnotatedTypeMetadata meta)
  {
    Environment env = ctx.getEnvironment();
    Map<String, Object> attr = meta.getAnnotationAttributes(
                                 ConditionalOnEnvProperty.class.getName());

    boolean shouldPropExist = (Boolean)attr.get("exists");
    String prop = (String)attr.get("value");

    boolean doesPropExist = env.getProperty(prop) != null;

    // doesPropExist    shouldPropExist    result
    //    true             true             true
    //    true             false            false
    //    false            true             false
    //    true             false            true
    return doesPropExist == shouldPropExist;
  }
}

...然后是使用该条件的注释。

/*
 * Condition returns true if myprop exists:
 * @ConditionalOnEnvProperty("myprop")
 *
 * Condition returns true if myprop does not exist
 * @ConditionalOnEnvProperty(value="myprop", exists=false)
 */
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Conditional(OnEnvironmentPropertyCondition.class)
public @interface ConditionalOnEnvProperty
{
  public String value();
  public boolean exists() default true;
}

您可以使用@PropertySource注释添加featuretoggles.properties到环境中。

于 2017-05-19T17:23:41.950 回答