Met
Met

Reputation: 3162

CDI Injection Outside Filters and Servlets in a Servlet 3.0 Container

I finally decided to have a look at Weld in Tomcat. When I deploy my app I see in the log:

"Tomcat 7 detected, CDI injection will be available in Servlets and Filters"

How can for example create an instance of a bean using the BeanManager outside a Filter/Servlet?

I have a bean:

@javax.inject.Named(value="CarService")
@javax.enterprise.context.RequestScoped
public class CarService implements Serializable{
.
.
.

and I want to create an instance of it using the BeanManager for the specified request context.

Context ctx = new InitialContext();
BeanManager manager = (BeanManager) ctx.lookup("java:comp/env/BeanManager");
// NOW WHAT?

If this can be done in a servlet/filter I am sure it can be done anywhere else but I just do not want to go through the Weld code and figure it out myself without asking first.

Thank you very much.

Upvotes: 0

Views: 1433

Answers (2)

Met
Met

Reputation: 3162

I already used this Seam code which gave me all I needed.

public static <T> T getContextualInstance(final BeanManager manager, final Class<T> type) {
        T result = null;
        Bean<T> bean = (Bean<T>) manager.resolve(manager.getBeans(type));
        if (bean != null) {
            CreationalContext<T> context = manager.createCreationalContext(bean);
            if (context != null) {
                result = (T) manager.getReference(bean, type, context);
            }
        }
        return result;
    }

Upvotes: 2

Bozho
Bozho

Reputation: 597016

Using the BeanManager is something that you should rarely do. The point is to use @Inject in places where you need dependencies (which is dependency injection). Using the manager is the "service-locator" pattern.

If you really need it, use manager.getBeans(yourDesiredClass), then pick one from the set and call manager.getReference(bean, theClass, ctx). ctx will be obtained by manager.createCreationalContext(bean)

Upvotes: 2

Related Questions