gpt4 book ai didi

spring - @Autowired Spring @Component 和 @ConditionalOnProperty

转载 作者:行者123 更新时间:2023-12-01 15:29:21 25 4
gpt4 key购买 nike

我可以用@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”的名称匹配是巧合;我的目标不是让它们相等,切换可以有任何名称。)

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

我知道我可以通过 @Configuration 实现这一点选择 @Bean 的类视属性(property)而定。但是当我这样做时,我必须在每次添加功能切换时添加一个新的 Configuration 类,这些 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();
}

}

最佳答案

我通过关注 this guide 做了你想做的事情.第一步是写一个 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;
}

您可以添加 featuretoggles.properties@PropertySource 的环境注解。

关于spring - @Autowired Spring @Component 和 @ConditionalOnProperty,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44074646/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com