@Autowired Spring @Component with @ConditionalOnProperty



我可以@Autowired Spring 4.x @Component s一起使用@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"的名称匹配是巧合;我的目的不是让它们相等,切换可以有任何名称。

这无法在Controller中自动连线featureUnsatisfiedDependencyException,说"没有可用的'功能'类型的合格 bean:预计至少有 1 个符合自动连线候选条件的 bean"。

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

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

我按照本指南做了你想做的事情。第一步是写一个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

相关内容

  • 没有找到相关文章

最新更新