2015-04-21 43 views
1

我很難與澤西島測試框架一起工作。如何使用hk2注入自定義工廠?

我有一個根資源。

@Path("sample") 
public class SampleResource { 

    @GET 
    @Path("path") 
    @Produces({MediaType.TEXT_PLAIN}) 
    public String readPath() { 
     return String.valueOf(path); 
    } 

    @Inject 
    private java.nio.file.Path path; 
} 

我準備了一個工廠,提供path

public class SamplePathFactory implements Factory<Path> { 

    @Override 
    public Path provide() { 
     try { 
      return Files.createTempDirectory(null); 
     } catch (final IOException ioe) { 
      throw new RuntimeException(ioe); 
     } 
    } 

    @Override 
    public void dispose(final Path instance) { 
     try { 
      Files.delete(instance); 
     } catch (final IOException ioe) { 
      throw new RuntimeException(ioe); 
     } 
    } 
} 

還有一個活頁夾。

public class SamplePathBinder extends AbstractBinder { 

    @Override 
    protected void configure() { 
     bindFactory(SamplePathFactory.class).to(Path.class); 
    } 
} 

最後,我的測試類。

public class SampleResourceTest extends ContainerPerClassTest { 

    @Override 
    protected Application configure() { 
     final ResourceConfig resourceConfig 
      = new ResourceConfig(SampleResource.class); 
     resourceConfig.register(SamplePathBinder.class); 
     return resourceConfig; 
    } 
} 

當我試圖測試,我得到了。

org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at SystemInjecteeImpl(requiredType=Path,parent=SampleResource,qualifiers={},position=-1,optional=false,self=false,unqualified=null,1916953383) 

我做錯了什麼?

回答

1

您的AbstractBinder s應該註冊爲實例,而不是一個類。所以要改變

resourceConfig.register(new SamplePathBinder()); 

,它應該工作

+0

能否請你看一看http://stackoverflow.com/q/29767581/330457? –