我如何使用HK2注入一个定制的工厂?(How can I inject a custom facto

2019-10-22 18:19发布

我有一个困难时期的球衣测试框架的工作。

我有一个根资源。

@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)

我做错了什么?

Answer 1:

AbstractBinder也应该被注册为实例 ,而不是作为一个阶级。 所以要改变

resourceConfig.register(new SamplePathBinder());

它应该工作



文章来源: How can I inject a custom factory using hk2?