2015-05-20 307 views
2

我有一个资源类依赖注入2.17

@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中嵌入模式,并添加初始化参数

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 我将如何注入服务模拟到控制器从测试?

+0

尝试'@ InjectParam' –

回答

2

在你的第二次尝试中(没有cdi依赖;使用HK2)你的绑定是不正确的。它应该是

bind(Implementation).to(Contract) 
// - i.e. 
bind(DemoServiceImpl.class).to(DemoService.class); 

你有其它的方式。

就测试而言,如果您在同一个包中(在项目的测试区域中)进行测试,您应该能够分配该服务,因为它是私有包。尽管个人,我已经习惯了构造注入的习惯。你可以做的另一件事是使用Jersey Test Framework。你可以看到一个完整的示例here,其中模拟服务注入

+0

可以请你回答如何注入依赖于JerseyTest这里http://stackoverflow.com/questions/30789297/is-它-可能使用的汗布-CDI功能于任何-JavaSE中的应用 – bl3e