Inject multible instances of a custom scoped bean
suikast42 Mar 14, 2014 9:12 AMHi guys,
I need a CDI Context behavour like EJB Stateful beans.
For example
@Inject
MyScopedBean bean1;
@Inject
MyScopedBean bean2;
So the bean1 and the bean2 should have two diffrent proxies.
The relevant part of my context implementation is:
@Override public <T> T get(final Contextual<T> contextual) { return null; } @Override public <T> T get(final Contextual<T> contextual, final CreationalContext<T> creationalContext) { Bean<T> bean = (Bean) contextual; if (creationalContext == null) { return null; } System.err.println("bean "+bean.hashCode() +" creationalContext "+creationalContext.hashCode()); MultiSessionScopeContextHolderV2.MultiSessionScopeInstance beanHolder = customScopeContextHolder.getBean(bean, creationalContext); if(beanHolder == null){ T instance = bean.create(creationalContext); MultiSessionScopeContextHolderV2.MultiSessionScopeInstance<T> customInstance = new MultiSessionScopeContextHolderV2.MultiSessionScopeInstance(bean, creationalContext, instance); customScopeContextHolder.putBean(customInstance); beanHolder = customScopeContextHolder.getBean(bean, creationalContext); } return (T) beanHolder.getInstance(); } }
I thought that Weld gives me a creational context per injectionpoint. Thats not so
After debugging I see that ContextBeanInstance<T> is responsible for that behaviour.
public T getInstance() { Container container = Container.instance(contextId); if (bean == null) { bean = container.services().get(ContextualStore.class).<Bean<T>, T>getContextual(id); } Context context = container.deploymentManager().getContext(bean.getScope()); T existingInstance = context.get(bean); if (existingInstance != null) { return existingInstance; } WeldCreationalContext<T> creationalContext; WeldCreationalContext<?> previousCreationalContext = currentCreationalContext.get(); if (previousCreationalContext == null) { creationalContext = new CreationalContextImpl<T>(bean); } else { creationalContext = previousCreationalContext.getCreationalContext(bean); } final CurrentInjectionPoint currentInjectionPoint = container.services().get(CurrentInjectionPoint.class); currentCreationalContext.set(creationalContext); try { // Ensure that there is no injection point associated currentInjectionPoint.push(EmptyInjectionPoint.INSTANCE); return context.get(bean, creationalContext); } finally { currentInjectionPoint.pop(); if (previousCreationalContext == null) { // ------>>>> ???? When is the context not null currentCreationalContext.remove(); } else { currentCreationalContext.set(previousCreationalContext); } } }
See my comment on line 28. The previousCreationalContext is always null and I get every time a new creationalcontext.
So the quetion is, is that possible to tell weld that it have to create one proxy and creationalcontext per injection??