Following up on Jersey + HK2 + Grizzly: Proper way to inject EntityManager?, I would like to understand how it is possible use dependency injection in classes which are
Statement: Implementation of Dependency Injection using Grizzly and Jersey
Please follow the below steps to do the same –
List item Create a class called Hk2Feature which implements Feature -
package com.sample.di;
import javax.ws.rs.core.Feature;
import javax.ws.rs.core.FeatureContext;
import javax.ws.rs.ext.Provider;
@Provider
public class Hk2Feature implements Feature {
public boolean configure(FeatureContext context) {
context.register(new MyAppBinder());
return true;
}
}
List item Create a class called MyAppBinder which extends AbstractBinder and you need to register all the services here like below –
package com.sample.di;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
public class MyAppBinder extends AbstractBinder {
@Override
protected void configure() {
bind(MainService.class).to(MainService.class);
}
}
List item Now, it’s time to write your own services and inject all the required services in your appropriate controllers like below code – package com.sample.di;
public class MainService {
public String testService(String name) {
return “Hi” + name + “..Testing Dependency Injection using Grizlly Jersey “;
}
}
package com.sample.di;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
@Path(“/main”)
public class MainController {
@Inject
public MainService mainService;
@GET
public String get(@QueryParam(“name”) String name) {
return mainService.testService(name);
}
@GET
@Path(“/test”)
@Produces(MediaType.APPLICATION_JSON)
public String ping() {
return “OK”;
}
}
Now hit the url http://localhost:8080/main?name=Tanuj and you will get your result. This is how you can achieve dependency injection in Grizzly Jersey application. Find the detailed implementation of the above skeleton in my repo. Happy Coding