I am trying to use Weld-SE for dependency injection in a dropwizard application. I can bootstrap Weld and inject in the Application class like so:
public class App extends Application<AppConfig> {
@Inject NameService service;
@Inject RestResource resource;
public static void main(String[] args) throws Exception {
Weld weld = new Weld();
WeldContainer container = weld.initialize();
App app = container.instance().select(App.class).get();
app.run(args);
weld.shutdown();
}
}
I have written a producer method in a separate class for the RestResource and this is also injected fine. However in the resource class the service is not injected:
@Path("/test")
@Produces(MediaType.APPLICATION_JSON)
public class RestResource {
@Inject NameService service;
@GET
public String test() {
return service.getName();
}
}
Here service is always null. Does anyone know how to make this work?
Dropwizard is using Jersey whose dependency injection is based on HK2 and not CDI. As a consequence you need to have a bridge between the two. This is what the jersey-gf-cdi
is for:
<dependency>
<groupId>org.glassfish.jersey.containers.glassfish</groupId>
<artifactId>jersey-gf-cdi</artifactId>
</dependency>
You only need to have that JAR in the classpath. You can see here a configuration for Jetty here: https://github.com/astefanutti/cdeye/blob/cd6d31203bdd17262aab12d992e2a730c4f8fdbd/webapp/pom.xml
And hereafter an example of CDI bean injection into JAX-RS resource: https://github.com/astefanutti/cdeye/blob/cd6d31203bdd17262aab12d992e2a730c4f8fdbd/webapp/src/main/java/io/astefanutti/cdeye/web/BeansResource.java