前端之家收集整理的这篇文章主要介绍了
rest – 如何使用Jersey将依赖项注入资源?,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下
代码:
@Path("stores")
class StoreResources {
private ServerConfig config;
@GET
public String getAll() {
//do some stuff with ServerConfig
}
}
我需要从外部将ServerConfig对象注入到此类中,并在getAll()方法中使用它.
有哪些可能的方法来实现它?我应该使用像Guice或Spring这样的DI框架吗?
@H_
404_8@
这是关于Jersey
http://javaswamy.blogspot.com/2010/01/making-jersey-work-with-spring.html下Spring注入的好
博客
结果是你使用注释来标记要注入的字段,这是一个示例资源
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();
}
}
为了我的目的,配置过于困难所以我使用静态弹簧解析器工厂来解析bean.例如.
private SimpleBean simpleBean = Springbeanfactory.getBean("mySimpleBean");