users@jersey.java.net

EJB Dependency Injection into a RESTFul Web Service (Jersey)

From: Jan Verbeke <Jan.Verbeke_at_realdolmen.com>
Date: Mon, 2 Mar 2009 16:43:38 +0100

Dear sir,

I'm currently a student working for a large it company. My task is to create back end and a to experiment with an RESTFul web service.
Also to develop with ejb 3.0 and perhaps the 3.1 but that's for later.

I read a blog from Paul Sandoz, http://blogs.sun.com/sandoz/entry/ejb_injection

I currently am running a RESTful web service, everything works fine but I have no idea how to inject a bean .
Do I inject it in the entity classes, in the converter in the service?
Some more info on how to instantiate the class and some info about the required parameters.
I have already worked with EJBeans so I recognized the lookup syntax.
I am also working with some beans atm.

The context. lookup has the following value ctx.lookup("Bean30#ejb.Bean30Remote");
It's a stateless session bean.

What I'm actually asking for is if you could provide a simple example with an entity, the corresponding service and converter and a simple EJB that is injected in the RESTFul web service.

The class from the blog:

package entities;

import com.sun.jersey.core.spi.component.ComponentContext;
import com.sun.jersey.core.spi.component.ComponentScope;
import com.sun.jersey.spi.inject.Injectable;
import com.sun.jersey.spi.inject.InjectableProvider;
import java.lang.reflect.Type;
import javax.ejb.EJB;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.ws.rs.ext.Provider;

@Provider
public class EJBProvider implements InjectableProvider<EJB, Type> {

public ComponentScope getScope() {
    return ComponentScope.Singleton;
}

public Injectable getInjectable(ComponentContext cc, EJB ejb, Type t) {
    if (!(t instanceof Class)) {
            return null;
    }
    try {
        Class c = (Class) t;
        Context ic = new InitialContext();

        final Object o = ic.lookup(c.getName());

        return new Injectable<Object>() {
        public Object getValue() {
            return o;
           }
        };
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
}

Greetz!