How can I inject a custom factory using hk2?

青春壹個敷衍的年華 提交于 2019-12-11 11:01:42

问题


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 AbstractBinders 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!