具有外部条件的spring eventListener

Jan*_*ski 6 spring event-handling

我需要一个灵活的过滤器,FooEvents用于遍布我的代码的多个EventListener.我可以使用@EventListener(condition ="event.enabled"),但我的过滤器需要分析fooEvent的许多属性.

我希望我可以在我的应用程序上下文中使用Predicate-Bean:

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

...

@EventListener(condition="${fooPredicate.test(event)}")
public void handle(FooEvent event) { ... }
Run Code Online (Sandbox Code Playgroud)

但我得到:

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

是否可以为EventListerns使用外部复杂的条件?或者至少定义具有复杂条件的全局侦听器并继承其行为而不重复完整条件?

xyz*_*xyz 9

您正在使用错误的定义,因为fooPredicate您需要使用"@"而不是"#"来将其解析为bean.请参阅10.5.13 Bean引用

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