Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring eventListener with external condition

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?

like image 717
Jan Galinski Avatar asked Jul 16 '17 00:07

Jan Galinski


1 Answers

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();
}
like image 56
xyz Avatar answered Oct 23 '22 09:10

xyz