簡體   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