[cdi-dev] Getting injection point from Bean#create
Jozef Hartinger
jharting at redhat.com
Thu Nov 20 15:42:19 EST 2014
The simplest thing you can do is:
Bean<InjectionPoint> bean = (Bean<InjectionPoint>)
manager.resolve(manager.getBeans(InjectionPoint.class));
InjectionPoint ip = (InjectionPoint) manager.getReference(bean,
InjectionPoint.class, manager.createCreationalContext(bean));
On 11/19/2014 05:06 PM, arjan tijms wrote:
> 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
> _______________________________________________
> cdi-dev mailing list
> cdi-dev at lists.jboss.org
> https://lists.jboss.org/mailman/listinfo/cdi-dev
>
> Note that for all code provided on this list, the provider licenses the code under the Apache License, Version 2 (http://www.apache.org/licenses/LICENSE-2.0.html). For all other ideas provided on this list, the provider waives all patent and other intellectual property rights inherent in such information.
More information about the cdi-dev
mailing list