Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
583 views
in Technique[技术] by (71.8m points)

java - How to inject a bean into a Spring Condition class?

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();
    }

}

And

@Component
public class MyProperties {...}

And

@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)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Condition, Spring Framework 5.0.8.RELEASE API documentation

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

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

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

You should rethink the design because

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

indicates that it's not quite right.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...