In this tutorial, we will learn how to applying conditions to event listeners via @EventListener.
@EventListener
@EventListener#condition attribute can be used to specify a condition. The condition is expressed in Spring Expression language (SpEL).
@EventListener#condition
package com.logicbig.example; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.event.EventListener; @Configuration public class EventListenerConditionExample { @Bean AListenerBean listenerBean() { return new AListenerBean(); } public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(EventListenerConditionExample.class); context.publishEvent(new MyEvent(1, "test message 1")); context.publishEvent(new MyEvent(5, "test message 5")); } private static class AListenerBean { @EventListener(condition = "#myEvent.code == 5") public void handleContextEvent(MyEvent myEvent) { System.out.println("event received: " + myEvent); } } private static class MyEvent { private String msg; private int code; public MyEvent(int code, String msg) { this.code = code; this.msg = msg; } public String getMsg() { return msg; } public int getCode() { return code; } @Override public String toString() { return "MyEvent{" + "msg='" + msg + '\'' + ", code=" + code + '}'; } } }
event received: MyEvent{msg='test message 5', code=5}
Dependencies and Technologies Used:
Version compatibilities of spring-context with this example:
Versions in green have been tested.