Java – using welding and dropwizard

I tried to use weld se for dependency injection in the dropwizard application I can boot weld and inject it into the application class, as shown below:

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 generator method in a separate class of restresource, which is also a good injection However, in the resource class, services will not be injected:

@Path("/test")
@Produces(MediaType.APPLICATION_JSON)
public class RestResource {
    @Inject NameService service;

    @GET
    public String test() {
        return service.getName();
    }
}

This service is always empty Who knows how to make this work?

Solution

Dropwizard is using Jersey, and its dependency injection is based on hK2 instead of CDI Therefore, you need to build a bridge between the two This is the purpose of Jersey GF CDI:

<dependency>
    <groupId>org.glassfish.jersey.containers.glassfish</groupId>
    <artifactId>jersey-gf-cdi</artifactId>
</dependency>

You just need to have the jar in the classpath You can see jetty's configuration here: https://github.com/astefanutti/cdeye/blob/cd6d31203bdd17262aab12d992e2a730c4f8fdbd/webapp/pom.xml

The following is an example of injecting CDI beans into jax-rs resources: https://github.com/astefanutti/cdeye/blob/cd6d31203bdd17262aab12d992e2a730c4f8fdbd/webapp/src/main/java/io/astefanutti/cdeye/web/BeansResource.java

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>