如何使用 Jersey 将依赖项注入资源?
我有以下代码:
@Path("stores")
class StoreResources {
private ServerConfig config;
@GET
public String getAll() {
//do some stuff with ServerConfig
}
}
我需要将 ServerConfig
对象从外部注入到此类中,并在 getAll()
方法内使用它。
有哪些可能的方法来实现它?我应该使用 Guice 或 Spring 等 DI 框架吗?
I'm having the following code:
@Path("stores")
class StoreResources {
private ServerConfig config;
@GET
public String getAll() {
//do some stuff with ServerConfig
}
}
And I need the ServerConfig
object to be injected into this class from outside and use it inside the getAll()
method.
What are the possible ways to achieve it? Should I use a DI framework like Guice or Spring?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一篇关于Jersey下Spring注入的好博客 http:// /javaswamy.blogspot.com/2010/01/making-jersey-work-with-spring.html
结果是您使用注释来标记要注入的字段,示例资源是
出于我的目的配置太困难了,所以我使用静态 spring 解析器工厂来解析 bean。例如。
This is a good blog about Spring injection under Jersey http://javaswamy.blogspot.com/2010/01/making-jersey-work-with-spring.html
The upshot is you use annotations to flag fields that are to be injected, an example resource being
For my purposes the configuration was excessively difficult so I used a static spring resolver factory to resolve the bean. eg.
您不需要 Spring 或 Guice 来注入 ServletConfig。 Jersey 通过它自己的注入机制来实现。请参阅 Jersey 示例分发版附带的 simple-servlet 示例。以下是将 HttpServletRequest 和 ServletConfig 注入资源的示例代码:
使用 Servlet 部署 JAX-RS 应用程序时,可使用 @Context 注入 ServletConfig、ServletContext、HttpServletRequest 和 HttpServletResponse。
You don't need Spring or Guice to inject a ServletConfig. Jersey does through its own injection mechanism. Refer to the simple-servlet example that comes with Jersey samples distribution. Here is the sample code that injects a HttpServletRequest and a ServletConfig onto a resource:
When deploying an JAX-RS application using Servlet then ServletConfig, ServletContext, HttpServletRequest and HttpServletResponse are available for injection using @Context.