When you have getClasses method in your Application then it tries to create instance for all the registered resources using the default constructor which is missing in our Resources class. One way is to create a default constructor and Inject the dependencies through setter Injection.
And then instead of overriding getClasses in ApplicationV1RS and ApplicationV2RS you override getSingletons. Since Resources can be Singleton.
Below are the changes that I made to make it work the way you want.
ApplicationV1RS.java
@ApplicationPath("v1")
public class ApplicationV1RS extends Application {
private Set
ApplicationV2RS.java
@ApplicationPath("v2")
public class ApplicationV2RS extends Application {
private Set singletons = new HashSet();
public ApplicationV2RS(@Context ServletContext servletContext) {
}
@Override
public Set getSingletons() {
Injector injector = Guice.createInjector(new HelloModule());
HelloResource helloResource = injector.getInstance(HelloResource.class);
UserResource userResource = injector.getInstance(UserResource.class);
singletons.add(helloResource);
singletons.add(userResource);
return singletons;
}
}
HelloResource.java
@Path("hello")
public class HelloResource {
@Inject
private IGreeterService greeter;
public HelloResource() {
}
@GET
@Path("{name}")
public String hello(@PathParam("name") final String name) {
return greeter.greet(name);
}
}
UserResource.java
@Path("user")
public class UserResource {
@Inject
private IUserService userService;
public UserResource() {
}
@GET
@Path("{name}")
public String hello(@PathParam("name") final String name) {
return userService.getUser(name);
}
}
Add @Singleton to your Service Classes.
Hope it helps.
I have also pushed the code to forked repo. check it out