如何将一个bean注入Spring Condition类? [英] How to inject a bean into a Spring Condition class?

查看:144
本文介绍了如何将一个bean注入Spring Condition类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在定义要检查的条件,以便稍后动态加载服务接口的两个实现之一.

I am defining conditions that I will check to dynamically load one of the two implementations of my service interface later.

@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 {...}

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

However, I am running into a runtime error as.

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对象.不允许吗?

Basically, it failed to initialize props object that has been auto-wired inside the condition implementation. Is that not allowed?

由于条件评估取决于该依赖关系提供的值,我该如何自动连接条件实现内部的另一个依赖关系?

How can I auto wire another dependency inside the condition implementation since my condition evaluation depends on a value provided by that dependency?

推荐答案

在要注册豆定义之前立即检查条件

Condition,Spring Framework 5.0.8.RELEASE API文档

Condition, Spring Framework 5.0.8.RELEASE API documentation

您不能将bean注入Condition实例,因为上下文中还没有bean定义 1 .

You can't inject a bean into a Condition instance because there are no bean-definitions in the context yet1.

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

Moreover, you are not supposed to work with beans within Condition classes:

条件必须遵循与BeanFactoryPostProcessor相同的限制,并且注意切勿与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文档

Condition, Spring Framework 5.0.8.RELEASE API documentation

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

You should rethink the design because

[...]我的状况评估取决于该依赖项提供的值.

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

表示不太正确.

1 确切地说,Spring已经为自己的需要注册了一些bean.

1 Precisely speaking, there are a few beans already registered by Spring for its own needs.

这篇关于如何将一个bean注入Spring Condition类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆