簡體   English   中英

Jersey 子資源中沒有 CDI 注入源

[英]CDI injection source not available in Jersey sub-resource

我在 Jersey 應用程序中使用 CDI。 在根資源上,CDI 注入按預期工作,但每當我返回子資源時,CDI 注入源都不可用。

我的根資源與子資源定位器:

@Path("")
public class MyResource {

    @Inject @Named("name") // works
    private String name;

    @Context
    private ResourceContext context;

    @Path("test2")
    public Object test2() {
        return MySubResource.class;
        //return context.getResource(MySubResource.class); // this does not work either
    }

}

子資源:

public class MySubResource {

    @Inject @Named("name") // error
    private String name;

    @GET
    public Response test() {
        return Response.ok("Name in sub resource: " + name).build();
    }

}

錯誤:

org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at SystemInjecteeImpl(requiredType=String,parent=MySubResource,qualifiers={@javax.inject.Named(value=name)},position=-1,optional=false,self=false,unqualified=null,1235803160)

我正在使用org.glassfish.jersey.ext.cdi:jersey-cdi1x和 Weld 依賴項,在 Undertow 上運行,並將 Weld servlet 偵聽器添加到部署中。

同樣,對根資源的相同注入確實有效。 @Named("name") String@ApplicationScoped生產者生成。

這不應該工作嗎? 我錯過了什么?

可用的最小示例 Maven 項目: https : //gitlab.com/Victor8321/jersey-sub-resource-cdi

注意:存在一個懸而未決的問題,但不確定官方對此的立場是什么: https : //java.net/jira/browse/JERSEY-3184

正如https://github.com/eclipse-ee4j/jersey/issues/3456所指出的,向子資源類添加一個虛擬的@Path("xyz")是一個“修復”。 但是,這會在虛擬路徑下暴露您的子資源。

僅通過 CDI 注入實例也可以( @Inject Instance<MySubResource> .. ),但是 Jersey 管理的資源不可用於注入,例如@Context HttpServletRequest

我發現了另外兩種完全有效的方法(CDI 注入和 JAX-RS 注入)並且沒有副作用(與@Path ):

  • 使用@Provider注釋子資源類。
  • register() ResourceConfig (或Application )中的子資源類。

這兩種方法似乎都有效,因為它們讓 Jersey - 反過來,CDI - 意識到這個類。

注意:我已經相應地更新了我的示例項目以供將來參考。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM