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

标签 java spring spring-boot annotations spring-4

我正在定义条件,稍后我将检查这些条件以动态加载我的服务接口(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/

相关文章:

java - 不支持的类版本错误 ireport java maven v raptor

java - 使用 SWT 围绕圆弧绘制边

java - 从 Spring Controller 获取 Web App 根目录

java - Rabbitmq 队列不会在服务器启动时自动创建

java - 在 Spring Web 应用程序中管理用户图像

mysql - Spring Boot - Hibernate 未正确保存日期

java - 线程池中出现任务拒绝错误

java - Java 中的执行器和守护进程

java - 如何从返回集合的方法返回错误消息

java - 在其抽象父类(super class)中使用任何嵌套子类的泛型类型