@EventListener注解
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface EventListener {
@AliasFor("classes") Class<?>[] value() default {};
@AliasFor("value") Class<?>[] classes() default {};
String condition() default "";
}
用法
- 使用value或者classes指定需要监听的事件类型;
- 如果只需要监听一种类型参数,则直接在此注解标注的方法参数上写处理的事件类型参数即可;
- 如果该注解标注的方法的返回值不是void,则会将返回值作为事件,继续发布,如果是数组或集合则分开发布;
- 该注解可以配合@Order注解一块使用来指定监听方法执行的顺序
- condition中可以写SpEL表达式,#root.event可以引用事件对象,#root.args可以引用方法参数
@EventListener注解使用示例
@Configuration
public class ListenerConfig {
@EventListener
public ApplicationEvent handApplicationEvent(ApplicationStartedEvent event) {
System.out.println("处理事件..." + event);
return new PayloadApplicationEvent(new Object(),new Object());
}
@EventListener
public void handPayloadApplicationEvent(PayloadApplicationEvent event) {
System.out.println("处理事件...2" + event);
}
}