繁体   English   中英

使用焊接与Dropwizard

[英]Using Weld with Dropwizard

我试图在dropwizard应用程序中使用Weld-SE进行依赖注入。 我可以引导Weld并在Application类中注入,如下所示:

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();
  }
}

我已经在RestResource的一个单独的类中编写了一个生成器方法,这也是很好的注入。 但是在资源类中,不会注入服务:

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

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

此服务始终为空。 有谁知道如何使这项工作?

Dropwizard正在使用Jersey,其依赖注入基于HK2而不是CDI。 因此,您需要在两者之间架起一座桥梁。 这就是jersey-gf-cdi的用途:

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

您只需要在类路径中拥有该JAR。 你可以在这里看到Jetty的配置: https//github.com/astefanutti/cdeye/blob/cd6d31203bdd17262aab12d992e2a730c4f8fdbd/webapp/pom.xml

以下是向JAX-RS资源注入CDI bean的示例: https//github.com/astefanutti/cdeye/blob/cd6d31203bdd17262aab12d992e2a730c4f8fdbd/webapp/src/main/java/io/astefanutti/cdeye/web/BeansResource.java

对于DropWizard 0.8.1和Weld 2.2,程序如下:

1)向pom.xml添加依赖项:

<dependency>
    <groupId>org.jboss.weld.servlet</groupId>
    <artifactId>weld-servlet-core</artifactId>
    <version>2.2.11.Final</version>
</dependency>
<dependency>
    <groupId>org.glassfish.jersey.ext.cdi</groupId>
    <artifactId>jersey-cdi1x</artifactId>
    <version>2.17</version>
</dependency>
<!-- the following additional dependencies are needed by weld -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jsp-api</artifactId>
    <version>2.0</version>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

2)将beans.xml文件添加到src / main / resources / META-INF并为应用程序包添加包含过滤器。 使用阴影罐时尤其需要 - 没有过滤器焊接将扫描阴影罐中的每个类。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:weld="http://jboss.org/schema/weld/beans">

    <weld:scan>
        <weld:include name="com.example.**" />
    </weld:scan>
</beans>

3)在您的应用程序类中注册Weld的监听器

@Override
public void run(Configuration conf, Environment env) throws Exception {
    env.servlets().addServletListeners(new org.jboss.weld.environment.servlet.Listener());
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM