我有以下代码:
@Path("stores")
class StoreResources {
private ServerConfig config;
@GET
public String getAll() {
//do some stuff with ServerConfig
}
}
我需要
ServerConfig
要从外部注入(inject)到此类中的对象,并在 getAll()
中使用它方法。有哪些可能的方法来实现它?我应该使用像 Guice 还是 Spring 这样的 DI 框架?
最佳答案
这是一篇关于Jersey下Spring注入(inject)的好博客http://javaswamy.blogspot.com/2010/01/making-jersey-work-with-spring.html
结果是您使用注释来标记要注入(inject)的字段,示例资源是
package com.km.services;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.sun.jersey.spi.inject.Inject;
import com.km.spring.SimpleBean;
@Path("/hello")
@Component
@Scope("request")
public class HelloResource {
@Inject private SimpleBean simpleBean;
@GET
@Produces("text/plain")
public String getMessage() {
return simpleBean.sayHello();
}
}
出于我的目的,配置非常困难,因此我使用了静态 Spring 解析器工厂来解析 bean。例如。
private SimpleBean simpleBean = SpringBeanFactory.getBean("mySimpleBean");
关于rest - 如何使用 Jersey 将依赖项注入(inject)资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4123027/