2

I'm using Jersey to create an REST API but i don't understand how to inject a depedency instance to my resource class as shown in my two example classes:

MyApplication.java

public class MyApplication {

  public static void main(String[] args) {
   MyDataProvider dataProvider = new MyDataProvider(args); <---- Dependency

   // ... boot 

   // Setting up REST API
   ResourceConfig config = new ResourceConfig();
   config.packages("org.foo.resources");
   ServletHolder servlet = new ServletHolder(new ServletContainer(config));

    Server server = new Server(port);
    ServletContextHandler context = new ServletContextHandler(server, "/*");
    context.addServlet(servlet, "/*");
    try {
        server.start();
        server.join();
    } catch (InterruptedException e) {
    } catch (Exception e) {
    } finally {
        server.destroy();
    }

  }
}

MyResource.java

@Path("myresource")
public class MyResource {

  private String name;
  private String description;

  @Context
  HttpServletRequest request;
  @Context
  SecurityContext context;

  @Inject
  MyDataProvider dataProvider; <------ How to do this?

  @GET
  @Produces(MediaType.APPLICATION_JSON)
  public MyResource myresource() {
     name = dataProvider.loadSomeFancyStuff();
     description = dataProvider.loadSomeAwesomeStuff();
  }
}

Of course a singleton class can hold data and the data can be fetched from inside the resource, but isn't there a better way without using singletons? I just found examples about how to inject classes instead of instances like this

Update

I read the linked thread, but i think my problem is different because i want to inject an instance from 'MyApplication' which is instantiated with parameters. As I understand the linked thread, it explains only how to inject a class instance instantiated by Jersey. Am I wrong here? If yes can please someone explain how to inject an already instantiated instance of 'MyDataProvider'.

Or more short: Where is GreetingService constructed and how does Jersey know which instance should be injected in the example 'basic-dependency-injection-using-jerseys', i may not link to?

alex
  • 5,516
  • 2
  • 36
  • 60
  • Look at the second highest scored answer in your linked post. – Paul Samsotha Aug 25 '17 at 14:04
  • 1
    Per your update: from linked post _"Also, instead of `bind(Class).to(Class)`, you can also `bind(Instance).to(Class)`, which will be automatically be a singleton.:"_. This is also explained in "basic-dependency-injection-using-jerseys" – Paul Samsotha Aug 25 '17 at 23:31
  • ok thank you, now i understand – alex Aug 26 '17 at 16:54

0 Answers0