2015-05-20 235 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