如何使用hk2注入自定义工厂? [英] How can I inject a custom factory using hk2?

查看:484
本文介绍了如何使用hk2注入自定义工厂?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难使用jersey测试框架.

I'm having a hard time to work with jersey test framework.

我有一个根资源.

@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的工厂.

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);
        }
    }
}

还有活页夹.

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;
    }
}

当我尝试测试时,我得到了.

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)

我做错了什么?

推荐答案

您的AbstractBinder应该注册为实例,而不是类.因此进行更改

Your AbstractBinders should be registered as an instance, not as a class. So make the change

resourceConfig.register(new SamplePathBinder());

它应该可以工作

这篇关于如何使用hk2注入自定义工厂?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆