gpt4 book ai didi

java - 如何将 bean 注入(inject) Spring Condition 类?

转载 作者:行者123 更新时间:2023-12-02 08:44:35 25 4
gpt4 key购买 nike

我正在定义条件,稍后我将检查这些条件以动态加载我的服务接口(interface)的两个实现之一。

@Component
public class IsPolicyEnabled implements Condition {

@Autowired
private MyProperties props;

@Override
public boolean matches(ConditionContext arg0, AnnotatedTypeMetadata arg1) {
return props.isPolicyEnabled();
}

}

@Component
public class MyProperties {...}

还有

@Service
@Conditional(IsPolicyEnabled.class)
public class ServiceA implements Service {...}

但是,我遇到了运行时错误。

java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: java.lang.NullPointerException
at com.xyz.utils.IsPolicyEnabled.matches(IsPolicyEnabled.java:9)
at org.springframework.context.annotation.ConditionEvaluator.shouldSkip(ConditionEvaluator.java:108)
at org.springframework.context.annotation.ConditionEvaluator.shouldSkip(ConditionEvaluator.java:88)
at org.springframework.context.annotation.ConditionEvaluator.shouldSkip(ConditionEvaluator.java:71)
at org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider.isConditionMatch(ClassPathScanningCandidateComponentProvider.java:515)

基本上,它无法初始化在条件实现中自动连接的 props 对象。不允许吗?

由于我的条件评估取决于该依赖项提供的值,因此如何在条件实现中自动连接另一个依赖项?

最佳答案

Conditions are checked immediately before the bean-definition is due to be registered [...]

Condition, Spring Framework 5.0.8.RELEASE API documentation

您无法将 Bean 注入(inject)到 Condition 实例中,因为上下文中还没有 Bean 定义1

此外,您不应该在 Condition 类中使用 bean:

Conditions must follow the same restrictions as BeanFactoryPostProcessor and take care to never interact with bean instances.

Condition, Spring Framework 5.0.8.RELEASE API documentation

你应该重新考虑设计,因为

[...] my condition evaluation depends on a value provided by that dependency.

表明它不太正确。

1 准确地说,Spring已经根据自己的需要注册了一些bean。

关于java - 如何将 bean 注入(inject) Spring Condition 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52071886/

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