【发布时间】:2015-08-02 07:31:54
【问题描述】:
我有一个资源类
@Path("/rest")
public class DemoResourceController {
@Inject
DemoService demoService;
@Path("/get/demo")
@GET
@Produces(APPLICATION_JSON)
public Response getDemoLists() {
List<String> demoList=demoService.getDemoList();
return Response.ok(demoList).build();
}
我尝试了帖子中的答案 Dependency injection with Jersey 2.0
如果我使用
compile group: "org.glassfish.jersey.ext.cdi" , name: "jersey-cdi1x" , version: "2.17"
compile group: "org.glassfish.jersey.ext.cdi" ,name: "jersey-weld2-se" , version: "2.17"
在启动服务器时我得到
org.jboss.weld.exceptions.IllegalArgumentException: WELD-001408:
Unsatisfied dependencies for type demoService with qualifiers @Default
[BackedAnnotatedField] @Inject DemoResourceController.demoService at injection point
如果我删除上述依赖项,那么我会得到
javax.servlet.ServletException: A MultiException has 3 exceptions. They are:
1. org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no
object available for injection at SystemInjecteeImpl(requiredType=DemoService,parent=DemoResourceController,qualifiers={},position=- 1,optional=false,self=false,unqualified=null,1952079126)**
2. java.lang.IllegalArgumentException: While attempting to resolve the dependencies of DemoResourceController errors were found
3. java.lang.IllegalStateException: Unable to perform operation: resolve on package.DemoResourceController
org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:421)
resourceconfig 类是
public class ApplicationConfig extends ResourceConfig {
public ApplicationConfig() {
register(new ApplicationBinder());
packages(..name of packages..);
}
活页夹类是
public class ApplicationBinder extends AbstractBinder{
@Override
protected void configure() {
bind(DemoService.class).to(DemoServiceImpl.class);
}
}
我在嵌入式模式下使用tomcat并添加init参数
Context ctx = tomcat.addContext("/", new File("web-app").getAbsolutePath());
Wrapper wrapper = ctx.createWrapper();
wrapper.addInitParameter("javax.ws.rs.Application","xx.xx.ApplicationConfig");
如何在控制器中注入服务? 注入是对其进行单元测试的首选方式(当服务实现时,比如 demoServiceImpl 正在调用另一个服务,比如 XService)并且单元测试不应该依赖于 Xservice,因此 demoServiceImpl 我如何从测试中将服务的模拟注入到控制器中?
【问题讨论】:
标签: java jax-rs cdi jersey-2.0