0

I have a system where there are three services. Each service has a container that holds config information and other information.

These containers also register their routes to the HTTP server. Now, I need a way to make the routes access these containers. Here is the function that registers container routes to the HTTP server.

public void initRoutes(ServletContextHandler servletContextHandler) {
    ResourceConfig resourceConfig = new ResourceConfig();

    // I want to register this class instance to the routes
    // so, basically do something like the following:
    // resourceConfig.inject(MyServiceContainer.class, this);

    ServletContainer container = new ServletContainer(resourceConfig);
    ServletHolder holder = new ServletHolder(container);
    holder.setInitOrder(0);
    holder.setInitParameter("jersey.config.server.provider.packages", "com.stackoverflow.my_service.rest");

    servletContextHandler.addServlet(holder, "/v1/my_service/*");
}

Here is an example resource:

@HTTPHandlerClass
@Path("/sessions")
public class Sessions {

    // And have something like the following here:
    // MyServiceContainer container

    @POST
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    @Produces(MediaType.APPLICATION_JSON)
    public Response createSession() {
        try {
            JSONObject requestBody = new JSONObject();
            this.container.sendTestRequest();
            return Response.ok(response.toString()).build();
        } catch(UnirestException e) {
            return Response.status(400).build();
        }
    }
}

I am using

org.glassfish.jersey -> version: 2.22

org.eclipse.jetty -> version: 9.3.9.v20160517

Everything I have read online confused me so much that I have no idea what to do anymore.

Community
  • 1
  • 1
Gasim
  • 7,615
  • 14
  • 64
  • 131
  • I can't really understand what it is you are trying to do. What is `MyServiceContainer.class` and what is `resourceConfig.inject(MyServiceContainer.class, this);` supposed to accomplish? – Paul Samsotha Jan 13 '17 at 14:22
  • I want to inject `MyServiceContainer` instance into my resource. MyServiceContainer is just a class. It doesn't matter what that class is. I have an instance of this class available to me and all I want to do is to inject that instance to resources. – Gasim Jan 13 '17 at 14:24
  • The link that you marked this one as duplicate is not helpful at all. I know how to inject a new component. I want to inject an existing component without using Singleton. If I am going to use singleton, I can just use the singleton instead of injecting it. – Gasim Jan 13 '17 at 14:43
  • `bind(instance).to(contract)`. This is explained in one of the answers – Paul Samsotha Jan 13 '17 at 14:47

0 Answers0