[cdi-dev] Getting injection point from Bean#create

arjan tijms arjan.tijms at gmail.com
Wed Nov 19 11:06:28 EST 2014


Hi,

In a producer method it's trivial to get access to an InjectionPoint
instance representing the point where the value produced by the
producer will be injected.

When registering a Bean manually from an extension using
AfterBeanDiscovery#addBean, this is not immediately obvious.

After some fumbling with the CDI APIs I came up with the following
code that seems to work on both Weld and OWB (didn't test CanDI yet).

It uses a small "dummy" class, which is used to grab an InjectionPoint off:

In a Bean:

public Object create(CreationalContext<Object> creationalContext) {

InjectionPoint injectionPoint = (InjectionPoint)
beanManager.getInjectableReference(
            resolve(beanManager,
InjectionPointGenerator.class).getInjectionPoints().iterator().next(),
creationalContext
);

With InjectionPointGenerator being the following class:

public class InjectionPointGenerator {
    @Inject
    private InjectionPoint injectionPoint;
}

And resolve being the following method:

public static <T> Bean<T> resolve(BeanManager beanManager, Class<T> beanClass) {
        Set<Bean<?>> beans = beanManager.getBeans(beanClass);

        for (Bean<?> bean : beans) {
            if (bean.getBeanClass() == beanClass) {
                return (Bean<T>)
beanManager.resolve(Collections.<Bean<?>>singleton(bean));
            }
        }

        return (Bean<T>) beanManager.resolve(beans);
    }

As mentioned, while this seems to work, I wonder if it's the best approach.

Kind regards,
Arjan


More information about the cdi-dev mailing list