Dependency injection in restful WS

2019-05-26 15:30发布

问题:

I have simple restful WS

@Path("basic")
public class ServiceRS
{

   private IServiceJAX service;

   @GET
   @Produces(MediaType.APPLICATION_JSON)
   @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
   public String find(@FormParam("searchRequest") final String searchRequest)
   {
//...
      final List<Info> response = service.find(search);
//...
   }

}  

Where IServiceJAX is @Local interface of jax-webservice. Can I inject IServiceJAX to ServiceRS using annotation?
I don't want use JNDI lookup...

回答1:

Sure, you can. Although I suppose there are other ways, I have successfully run a simple test project with a @Stateless @WebService, @Local implementation of an interface, injected through @EJB annotation into a @Stateless RESTFul web service annotated with @Path.

This is not properly a CDI injection as you have demanded, but it works nicely and probably fits your needs anyway.

IServiceJAX class:

public interface IServiceJAX {
    public String hello(String txt);
}

IServiceJAXImpl class:

@WebService(serviceName = "NewWebService")
@Local
@Stateless
public class IServiceJAXImpl implements IServiceJAX {

    @WebMethod(operationName = "hello")
    @Override
    public String hello(@WebParam(name = "name") String txt) {
        return "Hello " + txt + " !";
    }
}

ServiceRS class:

@Path("basic")
@Stateless
public class ServiceRS {

    @EJB private IServiceJAX wsi;

    @GET
    @Path("{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public String result(@PathParam("id") String id) {
        return wsi.hello(id);
    }
}

UPDATE

If you prefer CDI injection, you can keep the above code and simply remove @Local and @Stateless annotations from IServiceJAXImpl. You can inject an instance of this class using:

@Inject private IServiceJAX wsi;

instead of

@EJB private IServiceJAX wsi;