问题
I'm having a hard time to work with jersey test framework.
I have a root resource.
@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;
}
I prepared a factory providing the 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);
}
}
}
And a binder.
public class SamplePathBinder extends AbstractBinder {
@Override
protected void configure() {
bindFactory(SamplePathFactory.class).to(Path.class);
}
}
And, finally, my test class.
public class SampleResourceTest extends ContainerPerClassTest {
@Override
protected Application configure() {
final ResourceConfig resourceConfig
= new ResourceConfig(SampleResource.class);
resourceConfig.register(SamplePathBinder.class);
return resourceConfig;
}
}
When I tried to test, I got.
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)
What did I do wrong?
回答1:
Your AbstractBinder
s should be registered as an instance, not as a class. So make the change
resourceConfig.register(new SamplePathBinder());
and it should work
来源:https://stackoverflow.com/questions/29763889/how-can-i-inject-a-custom-factory-using-hk2