【问题标题】:Jetty Embedded, Jersey 2, WeldJetty Embedded, Jersey 2, 焊接
【发布时间】:2014-01-08 15:08:30
【问题描述】:

我使用的是 Jetty 9.1 和 Jersey 2.5.1。 Jersey 内置了对 Jetty 的支持,所以我这样启动我的服务器:

public static void main(String[] args) {

    URI baseUri = UriBuilder.fromUri("http://localhost/").port(8080).build();
    ResourceConfig config = ResourceConfig.forApplicationClass(MyApplication.class);

    Server server = JettyHttpContainerFactory.createServer(baseUri, config);
}

MyApplication 只需调用 this.packages(...) 来查找我的 REST api 类。

但是,REST api 类包含一个 @Inject 注释字段,应该由 WELD 注入。显然 WELD 没有启动(未启用 CDI 支持),而且更奇怪的是,看起来 HK2(由 Jersey 2 使用)正在尝试执行注入。

(在访问 REST 端点时,我有一个 org.glassfish.hk2.api.UnsatisfiedDependencyException)。

如何正确设置 WELD(最好以编程方式)?

【问题讨论】:

  • 确保您使用的是 Weld 2.2+,因为它只是修复了 Jetty 9.1+ 的一些 CDI 集成错误。

标签: java jetty jersey-2.0 weld


【解决方案1】:

我使用了 Weld SE:

import org.jboss.weld.environment.se.Weld;
import org.jboss.weld.environment.se.WeldContainer;

然后很简单

Weld weld = new Weld();
try {
    WeldContainer container = weld.initialize();

    URI baseUri = UriBuilder.fromUri("http://localhost/").port(8080).build();
    ResourceConfig config = ResourceConfig.forApplicationClass(MyApplication.class);

    Server server = JettyHttpContainerFactory.createServer(baseUri, config);

    server.join();

} catch (Exception e) {
    e.printStackTrace();
} finally {
    weld.shutdown();
}

请注意,HK2 将处理 REST 类,因此我必须编写一个活页夹来使注入在这些类中工作。 This question helped me a lot.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-23
    • 1970-01-01
    • 1970-01-01
    • 2016-03-23
    • 2016-03-03
    • 2013-06-27
    相关资源
    最近更新 更多