adam bien's blog

CDI Events: Obtaining The InjectionPoint From EventMetaData 📎

Starting with Java EE 7, a CDI event:


package com.airhacks.events;

import javax.enterprise.event.Event;
import javax.inject.Inject;

public class MetaDataResource {

    @Inject
    Event<String> event;

    public void fire() {
        event.fire("hey duke");
    }

}


is delivered with injectable javax.enterprise.inject.spi.EventMetadata:


import javax.enterprise.event.Observes;
import javax.enterprise.inject.spi.EventMetadata;
import javax.enterprise.inject.spi.InjectionPoint;

public class Listener {

    public void onArrival(@Observes String event, EventMetadata metaData) {
        InjectionPoint ip = metaData.getInjectionPoint();
        Class clazz = ip.getMember().getDeclaringClass();
        String fieldName = ip.getMember().getName();
        System.out.println(clazz.getName() + "-> " + fieldName);
    }

}

The code creates the following output:


 com.airhacks.events.MetaDataResource-> event

See you at Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.