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?