我正在定义条件,稍后我将检查这些条件以动态加载我的服务接口(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 [...]
您无法将 Bean 注入(inject)到 Condition
实例中,因为上下文中还没有 Bean 定义1。
此外,您不应该在 Condition
类中使用 bean:
Conditions must follow the same restrictions as
BeanFactoryPostProcessor
and take care to never interact with bean instances.
你应该重新考虑设计,因为
[...] 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/