I tried to do something similar by sharing the context with CDI beans in general on JBoss 7.1. Although this did not work for me, I'm not sure if it caused problems with the current state of JBoss7.1, maybe this will work for you?
What I did was something at startup that has access to the ServletContext (in my case, the JAX-RS Application , but probably a listener or servlet for you) access the bean area with the applications and set the ServletContext in it.
To connect to the CDI world, I used the recipe from the following URI to instantiate the bean: http://docs.jboss.org/weld/reference/1.1.0.Final/en-US/html/extend.html#d0e4978
The corresponding code looks something like this:
@SuppressWarnings("unchecked") public <T> T getBean(Class<T> instanceClass) throws NamingException { BeanManager beanManager = (BeanManager) InitialContext.doLookup("java:comp/BeanManager"); AnnotatedType<Object> annotatedType = (AnnotatedType<Object>) beanManager.createAnnotatedType(instanceClass); InjectionTarget<Object> injectionTarget = beanManager.createInjectionTarget(annotatedType); CreationalContext<Object> context = beanManager.createCreationalContext(null); Object instance = injectionTarget.produce(context); injectionTarget.inject(instance, context); injectionTarget.postConstruct(instance); return (T) instance; }
which can then be set to a bean, which looks like this:
package some.package; import javax.enterprise.context.ApplicationScoped; import javax.servlet.ServletContext; @ApplicationScoped public class AppContext { private ServletContext servletContext; public ServletContext getServletContext() { return servletContext; } public void setServletContext(ServletContext servletContext) { this.servletContext = servletContext; } }
using a fragment like:
getBean(AppContext.class).setServletContext(servletContext);
in your starter code. Then you can simply @Inject use the context in any CDI construct in which you want to use it ... provided that it starts after your init servlet or something else.
For instance:
@Inject private AppContext appContext;
I will be wondering if this works in other situations ...
source share