spring eventListener with external condition

纵然是瞬间 提交于 2019-12-01 02:31:31

问题


I need a flexible filters for FooEvents for multiple EventListeners all over my code. I can use @EventListener(condition="event.enabled"), but my filters require many attributes of fooEvent to be analysed.

I was hoping that I could use a Predicate-Bean from my Application Context:

@Component
public class FooPredicate implements Predicate<FooEvent> {
   public boolean test(FooEvent event) {...}
}

...

@EventListener(condition="${fooPredicate.test(event)}")
public void handle(FooEvent event) { ... }

But I get:

org.springframework.expression.spel.SpelEvaluationException: EL1011E: 
   Method call: Attempted to call method 
   test(org.springframework.context.PayloadApplicationEvent) on null 
   context object

Is it possible to use external, complex conditions for EventListerns? Or at least to define global listeners with complex conditions and inherit their behavior without repeating the full conditions?


回答1:


You're using the wrong definition, as fooPredicate is a spring bean you need to use '@' instead of '#' to resolve it as a bean. see 10.5.13 Bean references

@EventListener(condition="@fooPredicate.test(#event)")
public void handle(FooEvent event) {
    System.out.println();
}


来源:https://stackoverflow.com/questions/45123796/spring-eventlistener-with-external-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!