【问题标题】:How do I inject Jersey beans into Quartz job in Weld?如何在 Weld 中将 Jersey bean 注入到 Quartz 工作中?
【发布时间】:2012-05-22 08:36:14
【问题描述】:

我在 Glassfish 和 jetty-servlet 中都有一个纯 JAX-RS 应用程序。我正在尝试将一些 bean 注入 Quartz 作业中。

我已经用 @javax.inject.Inject 注释了 Job 字段,但我也相信我需要让 Job factory 可用于容器,反之亦然 - 我在这里有点迷失了从什么开始。

我该如何完成?

【问题讨论】:

  • Victor 你想@Inject 工作到你的其他 bean 中吗?
  • 不,反过来。我的工作基本上需要一个记录器和一个 DAO。

标签: java dependency-injection jersey quartz-scheduler jboss-weld


【解决方案1】:

您好 Victor,没有更多关于您的应用程序的详细信息,我假设您在 servlet 容器中运行。使用“纯”JAX-RS 应用程序无法做到这一点。

不过,我建议您使用 CDI(Weld 或 OpenWebBeans)。然后,您可以使用 Deltaspike 启用 Quartz 作业中的请求上下文,以获取对请求范围 bean 的引用。

在你的 servlet 容器中启用 Weld 相当 simple

关于在 HTTP 请求之外启用请求上下文的指南是可用的here

默认情况下,您不能将 @RequestScoped bean 注入到您的石英作业中(没有 HTTP 请求,因此没有请求上下文)。要解决这个问题,您可以通过上面的链接启用请求上下文,或者(可能是我的方法)将 @Dependent 范围 bean(它完成工作)注入您的 JAX RS bean(基本上是包装器),然后您可以轻松获取引用到您的石英作业中的 @Dependent 范围 bean。

这是我的 web.xml 和 pom.xml,用于在 jetty 中运行 Weld 和 Jersey,您将需要 jetty-plus、jetty-jndi 和 Weld 依赖项。

这里有一些关于在 jetty 中设置 JNDI 的 info,但是我不使用这种方法,因为我将 jetty 作为 SE 应用程序中的嵌入式容器启动,这是我所做的代码 sn-p:

String[] configurationClasses =
{
    "org.eclipse.jetty.webapp.WebInfConfiguration",
    "org.eclipse.jetty.webapp.WebXmlConfiguration",
    "org.eclipse.jetty.webapp.MetaInfConfiguration",
    "org.eclipse.jetty.webapp.FragmentConfiguration",
    "org.eclipse.jetty.plus.webapp.EnvConfiguration",
    "org.eclipse.jetty.webapp.JettyWebXmlConfiguration"
};
WebAppContext webapp = new WebAppContext();
webapp.setConfigurationClasses(configurationClasses);
webapp.setDescriptor("/path/to/webapp/WEB-INF/web.xml");
webapp.setContextPath("/");
webapp.setResourceBase("/path/to/webapp");
webapp.setClassLoader(Thread.currentThread().getContextClassLoader());

【讨论】:

  • 很抱歉,我太不具体了。我相信,我在 jetty-servlet 中使用 Weld。现在更新问题。
  • 能否也分享一下您的pom.xml?
  • 谢谢。非常相似的配置对我来说无法启动:IllegalStateException: Nothing to bind for name javax.enterprise.inject.spi.BeanManager/default at org.eclipse.jetty.plus.webapp.PlusDescriptorProcessor.bindEntry(PlusDescriptorProcessor.java:890)。你能帮我看看为什么吗?
  • @VictorSergienko 我已经包含了我在 jetty 中启用 jndi 所做的工作,我一直想写博客关于让 jersey、weld、jsf2 和 jetty 在 j2se 应用程序中都玩得很好,所以我会在周末尝试这样做,并将其示例项目粘贴在 github 中。
  • 再次感谢 DeltaSpike,这是我缺少的主要部分。遗憾的是,我没有自己创建 Context 的奢侈。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-05
  • 2013-04-05
  • 1970-01-01
  • 2011-09-19
  • 2011-06-05
  • 1970-01-01
  • 2014-06-27
相关资源
最近更新 更多