Java 使用 Jersey 和 Guice 进行 RESTful 服务的实用建议

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2669926/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:36:31  来源:igfitidea点击:

Practical advice on using Jersey and Guice for RESTful service

javaguicejerseyjax-rsjsr330

提问by toolbear

From what I can find online, the state of the art for Guice + Jersey integration has stagnated since 2008 when it appears both teams reached an impasse. The crux of the issue is that JAX-RS annotations perform field and method injection and this doesn't play nicely with Guice's own dependency injection.

从我在网上找到的信息来看,自 2008 年两支球队似乎陷入僵局以来,Guice + Jersey 整合的最新进展就停滞不前了。问题的关键是 JAX-RS 注释执行字段和方法注入,这与 Guice 自己的依赖注入不能很好地配合。

A few examples which I've found don't go far enough to elucidate:

我发现的一些例子不足以说明:

  • Iqbalyusuf's post on Jersey + Guice on Google App Engine Javasuffers from a lot of boilerplate (manually getting and calling the injector). I want binding and injection should happen behind the scenes via Guice annotations.

  • Jonathan Curran's article Creating a RESTful service with Jersey, Guice, and JSR-250gave me hope because it's much more current (2010), but went no further than showing how to start up a Jersey service inside of a Guice ServletModule. However, there are no examples of doing any real dependency injection. I suppose that was left as an exercise for the reader. Curran's post may in fact be the correct first step towards wiring up Guice and Jersey and so I plan on starting with that.

  • tantalizingly James Strachan writes:

    JAX-RS works well with dependency injection frameworks such as Spring, Guice, GuiceyFruit or JBossMC - you can basically pick whichever one you prefer.

    But I see no evidence that is true from a practitioner's point of view.

  • Iqbalyusuf 在Jersey + Guice on Google App Engine Java 上的帖子受到大量样板文件的影响(手动获取和调用注入器)。我希望绑定和注入应该通过 Guice 注释在幕后发生。

  • Jonathan Curran 的文章用 Jersey、Guice 和 JSR-250 创建 RESTful 服务给了我希望,因为它是最新的(2010 年),但只是展示了如何在 Guice ServletModule 中启动 Jersey 服务。但是,没有进行任何真正依赖注入的示例。我想这是留给读者的练习。Curran 的帖子实际上可能是连接 Guice 和 Jersey 的正确第一步,所以我计划从这个开始。

  • 诱人的James Strachan 写道

    JAX-RS 与 Spring、Guice、GuiceyFruit 或 JBossMC 等依赖注入框架配合得很好——你基本上可以选择你喜欢的任何一个。

    但我没有看到从从业者的角度来看是真实的证据。

What I find lacking are practical examples and explanations on how to combine JAX-RS and Guice annotations. For instance:

我发现缺少的是关于如何结合 JAX-RS 和 Guice 注释的实际示例和解释。例如:

  • I believe I cannot use constructor injection with any resource as Jersey wants to control this
  • I'm uncertain whether I can combine @Inject with @PathParam, @QueryParam, et al.
  • How to use injection in a MessageBodyWriter implementation
  • 我相信我不能对任何资源使用构造函数注入,因为 Jersey 想要控制它
  • 我不确定是否可以将 @Inject 与 @PathParam、@QueryParam 等结合起来。
  • 如何在 MessageBodyWriter 实现中使用注入

Does anyone have examples, preferably with source, of non-trivial application which combines Jersey and Guice without sacrificing one or the other in the process? I'm keeping on this road regardless, but the bits and pieces on the Jersey and Guice lists makes me think I'm repeating the work of others who came before me.

有没有人有例子,最好有来源,结合 Jersey 和 Guice 而不牺牲一个或另一个的非平凡应用程序?无论如何我都在这条路上走,但泽西和吉斯名单上的点点滴滴让我觉得我在重复我之前的其他人的工作。

采纳答案by Nehc

Guice integration with Jersey has not stagnated. The opposite is true. Thanks to Paul and his cohorts behind Jersey, the latest 1.7 release contains a special JerseyServletModule class to work with Guice-based servlets. Guice-based constructor injection into JAX-RS resource works!The issue is using JAX-RS annotations such as @QueryParam in the constructor of a JAX-RS resource. You don't need it! You use Guice for POJO injection all the way including singletons. Then JAX-RS is just icing on the cake for parsing HTTP-based RESTful APIs such as URL path, query parameters, content-type and etc. You don't need an "industrial strength" example either. Both Guice and Jersey are already battle tested. You just need a complete working example to see how it works. Then you can experiment advanced features on your own. Check out the following link for a complete example using Guice 3.0 and Jersey 1.7, which are all latest releases:
http://randomizedsort.blogspot.com/2011/05/using-guice-ified-jersey-in-embedded.html

Guice 与 Jersey 的整合并未停滞。事实正好相反。感谢 Paul 和他支持 Jersey 的团队,最新的 1.7 版本包含一个特殊的 JerseyServletModule 类来处理基于 Guice 的 servlet。基于 Guice 的构造函数注入 JAX-RS 资源有效!问题是在 JAX-RS 资源的构造函数中使用了 JAX-RS 注释,例如 @QueryParam。你不需要它!您一直使用 Guice 进行 POJO 注入,包括单例。那么 JAX-RS 只是为解析基于 HTTP 的 RESTful API(例如 URL 路径、查询参数、内容类型等)锦上添花。您也不需要“行业实力”示例。吉斯和泽西岛都已经过战斗测试。您只需要一个完整的工作示例即可了解它是如何工作的。然后您可以自己试验高级功能。查看以下链接以获取使用 Guice 3.0 和 Jersey 1.7 的完整示例,它们都是最新版本:http:
//randomizedsort.blogspot.com/2011/05/using-guice-ified-jersey-in-embedded.html

回答by Jonas

I believe I cannot use constructor injection with any resource as Jersey wants to control this

我相信我不能对任何资源使用构造函数注入,因为 Jersey 想要控制它

You cannot use guice's constructor injection because creation of resource is managed by jersey. In this case you can use jersey's @Injectannotation before constructor parameter you want to get injected:

你不能使用 guice 的构造函数注入,因为资源的创建是由 jersey 管理的。在这种情况下,您可以@Inject在要注入的构造函数参数之前使用球衣的注释:

public NewsResource(@Inject NewsService service)

回答by Sunny Gleason

I created a Guice/Jersey/Jetty/Hymanson sample application here:

我在这里创建了一个 Guice/Jersey/Jetty/Hymanson 示例应用程序:

http://github.com/sunnygleason/j4-minimal

http://github.com/sunnygleason/j4-minimal

If you have any questions or suggestions for how to improve the example, feel free to message me via github. The goal is to make this a very accessible introduction to REST on the Java stack.

如果您对如何改进示例有任何问题或建议,请随时通过 github 给我留言。目标是使其成为 Java 堆栈上 REST 的一个非常易于理解的介绍。

Hope this helps - have a great day!

希望这会有所帮助 - 祝您有美好的一天!

-Sunny

-阳光

回答by Scott

I was having similar problems initially trying to use Guice to do constructor injection on my Jersey annotated classes, but eventually got it working, albeit with a fairly trivial application.

我最初尝试使用 Guice 对我的 Jersey 注释类进行构造函数注入时遇到了类似的问题,但最终让它工作了,尽管应用程序相当简单。

I followed the instructions here: jersey-guice javadoc

我按照这里的说明操作:jersey-guice javadoc

The trick in my case was that I needed to remove the standard Jersey configuration from my web.xml (like the Jersey ServletContainer) and keep only the Guice listener and Guice filter. Once I did that Guice was being called to create my JAX-RS annotated object, and Jersey was injecting my JAX-RS annotated methods (like @GET, etc.) as expected.

在我的案例中,技巧是我需要从我的 web.xml 中删除标准 Jersey 配置(如 Jersey ServletContainer)并只保留 Guice 侦听器和 Guice 过滤器。一旦我这样做了,Guice 就会被调用来创建我的 JAX-RS 注释对象,而 Jersey 正在按预期注入我的 JAX-RS 注释方法(如 @GET 等)。

回答by Daniel Bimschas

Inspired by Sunnys sample application I've created a similar sample project that uses standard WAR files for deployment, e.g. in Apache Tomcat. You can find the project here:

受 Sunnys 示例应用程序的启发,我创建了一个类似的示例项目,该项目使用标准 WAR 文件进行部署,例如在 Apache Tomcat 中。你可以在这里找到这个项目:

https://github.com/danbim/template-guice-jersey-tomcat

https://github.com/danbim/template-guice-jersey-tomcat

Have fun! Daniel

玩得开心!丹尼尔

回答by mckamey

These examples were all great starts for me, but I wanted a full MVC stack using Jersey-Guice at it's core. I've been working on refining that for sometime. As of this week this MVC stack is fully deployed to Maven Central repository as an archetype. This means you can now create a new Jersey-Guice stack with one Maven command:

这些示例对我来说都是很好的开始,但我想要一个完整的 MVC 堆栈,使用 Jersey-Guice 作为其核心。我一直在努力改进它有一段时间了。截至本周,此 MVC 堆栈已作为原型完全部署到 Maven 中央存储库。这意味着您现在可以使用一个 Maven 命令创建一个新的 Jersey-Guice 堆栈:

mvn archetype:generate \
    -DarchetypeGroupId=org.duelengine \
    -DarchetypeArtifactId=duel-mvc-archetype \
    -DarchetypeVersion=0.2.1

This automatically generates your own project with you specified package naming so you don't have to manually edit a template project.

这会使用您指定的包命名自动生成您自己的项目,因此您不必手动编辑模板项目。

See the project Readme.md for more details: https://bitbucket.org/mckamey/duel-mvc

看到项目Readme.md了解更多详情:https://bitbucket.org/mckamey/duel-mvc

Details on the dual-side views (client-side template & server-side views) I use are here: https://bitbucket.org/mckamey/duelbut you could replace with whatever you use.

我使用的双向视图(客户端模板和服务器端视图)的详细信息在这里:https: //bitbucket.org/mccamey/duel但您可以替换为您使用的任何内容。

回答by Le Hibou

I found an interesting project for lightweight Jetty+Guice+Hymanson web services: https://github.com/talis/jersey-common/

我发现了一个有趣的轻量级 Jetty+Guice+Hymanson Web 服务项目:https: //github.com/talis/jersey-common/

回答by stickfigure

GWizardincludes a module that gives you out-of-the-box integration between Jersey2 and Guice. Here's an example of a complete JAX-RS service:

GWizard包含一个模块,可让您在 Jersey2 和 Guice 之间进行开箱即用的集成。下面是一个完整的 JAX-RS 服务示例:

public class Main {
    @Path("/hello")
    public static class HelloResource {
        @GET
        public String hello() {
            return "hello, world";
        }
    }

    public static class MyModule extends AbstractModule {
        @Override
        protected void configure() {
            bind(HelloResource.class);
        }
    }

    public static void main(String[] args) throws Exception {
        Guice.createInjector(new MyModule(), new JerseyModule()).getInstance(Run.class).start();
    }
}

Note that this is based on the Squarespace jersey2-guice adapter, which may not function properly with future point releases of Jersey. GWizard also offers a RESTEasy JAX-RS module, which is preferred.

请注意,这是基于Squarespace jersey2-guice 适配器,它可能无法在 Jersey 的未来版本中正常运行。GWizard 还提供了一个 RESTEasy JAX-RS 模块,这是首选。

Here is a blog entry about this that might help: http://blorn.com/post/107397841765/guice-and-jersey-2-the-easy-way

这是一篇关于此的博客条目,可能会有所帮助:http: //blorn.com/post/107397841765/guice-and-jersey-2-the-easy-way

回答by Alex Ntousias

Although Sunny Gleason's example is great, it is a bit outdated now.

尽管 Sunny Gleason 的例子很棒,但它现在有点过时了。

So, after struggling a lot today trying to make Guice and Jersey play nice with each other, I created the following sample project to get you started:

所以,在今天努力让 Guice 和 Jersey 相互配合之后,我创建了以下示例项目来帮助您入门:

https://github.com/MaliciousMustard/gradle-guice-jersey-jetty

https://github.com/MaliciousMustard/gradle-guice-jersey-jetty

This project is using the following technologies:

该项目使用以下技术:

  1. Guice for DI
  2. Jersey for the RESTful API
  3. Hymanson for POJO to JSON mapping
  4. Jetty for the web-server
  5. Gradle
  1. DI 指南
  2. 用于 RESTful API 的 Jersey
  3. Hymanson 用于 POJO 到 JSON 的映射
  4. 用于 Web 服务器的 Jetty
  5. 摇篮

I guess the most important thing is that you don't have to explicitly specify every new resource class you're adding. As long as you're adding them to the package that is being scanned (look at malicious.mustard.modules.JerseyModule), they will be found automatically!

我想最重要的是您不必明确指定要添加的每个新资源类。只要您将它们添加到正在扫描的包中(查看malicious.mustard.modules.JerseyModule),就会自动找到它们!