我正在定义条件,稍后我将检查这些条件以动态加载我的服务接口的两个实现之一。
@Component
public class IsPolicyEnabled implements Condition {
@Autowired
private MyProperties props;
@Override
public boolean matches(ConditionContext arg0, AnnotatedTypeMetadata arg1) {
return props.isPolicyEnabled();
}
}
And
@Component
public class MyProperties {...}
And
@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 对象。这是不允许的吗?
由于我的条件评估取决于该依赖项提供的值,因此如何在条件实现中自动连接另一个依赖项?
条件已检查就在之前bean 定义将被注册 [...]
Condition, Spring Framework 5.0.8.RELEASE API documentation https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/Condition.html
You can't inject a bean into a Condition
instance because there are no bean-definitions in the context yet1.
此外,你不应该在以下范围内使用beanCondition
课程:
条件必须遵循与以下相同的限制BeanFactoryPostProcessor
and 注意不要与 bean 实例交互.
Condition, Spring Framework 5.0.8.RELEASE API documentation https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/Condition.html
你应该重新考虑设计,因为
[...]我的状况评估取决于该依赖性提供的值。
表明它不太正确。
1 Precisely speaking, there are a few beans already registered by Spring for its own needs.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)